我想在while循环中添加一个delay/sleep:
我是这样试的:
alert('hi');
for(var start = 1; start < 10; start++) {
setTimeout(function () {
alert('hello');
}, 3000);
}
只有第一种情况是正确的:在显示alert('hi')后,它将等待3秒,然后alert('hello')将显示,但随后alert('hello')将不断重复。
我想要的是,在警报('hello')显示3秒后警报('hi'),然后它需要等待3秒的第二次警报('hello'),以此类推。
/*
Use Recursive and setTimeout
call below function will run loop loopFunctionNeedCheck until
conditionCheckAfterRunFn = true, if conditionCheckAfterRunFn == false : delay
reRunAfterMs miliseconds and continue loop
tested code, thanks
*/
function functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn,
loopFunctionNeedCheck) {
loopFunctionNeedCheck();
var result = conditionCheckAfterRunFn();
//check after run
if (!result) {
setTimeout(function () {
functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn, loopFunctionNeedCheck)
}, reRunAfterMs);
}
else console.log("completed, thanks");
//if you need call a function after completed add code call callback in here
}
//passing-parameters-to-a-callback-function
// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function () {
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function () {
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
//test code:
var result = 0;
console.log("---> init result is " + result);
var functionNeedRun = function (step) {
result+=step;
console.log("current result is " + result);
}
var checkResultFunction = function () {
return result==100;
}
//call this function will run loop functionNeedRun and delay 500 miliseconds until result=100
functionRepeatUntilConditionTrue(500, checkResultFunction , functionNeedRun.bind(null, 5));
//result log from console:
/*
---> init result is 0
current result is 5
undefined
current result is 10
current result is 15
current result is 20
current result is 25
current result is 30
current result is 35
current result is 40
current result is 45
current result is 50
current result is 55
current result is 60
current result is 65
current result is 70
current result is 75
current result is 80
current result is 85
current result is 90
current result is 95
current result is 100
completed, thanks
*/
试试这个
var arr = ['A','B','C'];
(function customLoop (arr, i) {
setTimeout(function () {
// Do here what you want to do.......
console.log(arr[i]);
if (--i) {
customLoop(arr, i);
}
}, 2000);
})(arr, arr.length);
结果
A // after 2s
B // after 2s
C // after 2s
您可以创建一个承诺setTimeout的睡眠函数。这使您可以使用async/await来编写代码,而无需回调和熟悉的for循环控制流。
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
(async () => {
对于(设I = 0;I < 10;我+ +){
console.log(我);
等待睡眠(1000);
}
console.log(“完成”);
}) ();
在Node中,你可以使用计时器/承诺来避免承诺步骤(如果旧版本的Node不支持该功能,上面的代码也可以工作):
const {setTimeout: sleep} = require("timers/promises");
// same code as above
无论如何,由于JS是单线程的,超时是异步的是一件好事。如果不这样做,浏览器就没有机会重新绘制UI,从而导致用户的界面冻结。
非常简单的单行解决方案,具有实际的异步等待延迟(没有排队setTimeout):
下面的(自动执行匿名)函数在循环之间创建一个实际的延迟,而不是具有不同超时的多个settimeout,这可能会弄乱内存。
在100个循环中的每一个循环中,它都等待一个新的承诺来解决。
这只发生在setTimeout '允许'它在90ms后。在此之前,代码将被async-await / pending Promise阻塞。
(async () => {
For(令i=0;我< 100;我+ +){
等待新的承诺((resolve) => {setTimeout(() =>{文档。我写(“${}”);解决(true)}, 90)});
}
})()