Java while循环里延时_如何在JavaScript循环中添加延迟?

我想在while循环中添加一个延迟/睡眠:

我这样尝试过:

alert('hi');

for(var start = 1; start < 10; start++) {

setTimeout(function () {

alert('hello');

}, 3000);

}

只有第一个场景是真实的:显示后alert('hi')它会等待3秒,然后alert('hello')将被显示,但随后alert('hello')会反复不断。

我想要的是在alert('hi')之后3秒钟显示alert('hello')之后,它需要等待3秒才能第二次出现alert('hello') ,依此类推。

#1楼

我可能会使用setInteval 。 像这样,

var period = 1000; // ms

var endTime = 10000; // ms

var counter = 0;

var sleepyAlert = setInterval(function(){

alert('Hello');

if(counter === endTime){

clearInterval(sleepyAlert);

}

counter += period;

}, period);

#2楼

/*

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

*/

#3楼

我使用Bluebird的Promise.delay和递归进行此操作。

function myLoop(i) { return Promise.delay(1000) .then(function() { if (i > 0) { alert('hello'); return myLoop(i -= 1); } }); } myLoop(3);

#4楼

这是我用于遍历数组的函数:

function loopOnArrayWithDelay(theArray, delayAmount, i, theFunction, onComplete){

if (i < theArray.length && typeof delayAmount == 'number'){

console.log("i "+i);

theFunction(theArray[i], i);

setTimeout(function(){

loopOnArrayWithDelay(theArray, delayAmount, (i+1), theFunction, onComplete)}, delayAmount);

}else{

onComplete(i);

}

}

您可以这样使用它:

loopOnArrayWithDelay(YourArray, 1000, 0, function(e, i){

//Do something with item

}, function(i){

//Do something once loop has completed

}

#5楼

在ES6(ECMAScript 2015)中,您可以使用生成器和间隔来进行延迟迭代。

生成器是ECMAScript 6的新功能,可以暂停和恢复。 调用genFunc不会执行它。 相反,它返回一个所谓的生成器对象,使我们可以控制genFunc的执行。 genFunc()最初在其主体的开头暂停。 方法genObj.next()继续执行genFunc,直到下一个屈服为止。 (探索ES6)

代码示例:

let arr = [1, 2, 3, 'b']; let genObj = genFunc(); let val = genObj.next(); console.log(val.value); let interval = setInterval(() => { val = genObj.next(); if (val.done) { clearInterval(interval); } else { console.log(val.value); } }, 1000); function* genFunc() { for(let item of arr) { yield item; } }

因此,如果您使用的是ES6,那是实现延迟循环的最优雅的方法(我认为)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值