我想在while
循環中添加一個延遲/睡眠: html
我這樣嘗試過: ajax
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')
,依此類推。 app
我可能會使用setInteval
。 像這樣, ide
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);
/* 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 */
我使用Bluebird的Promise.delay
和遞歸進行此操做。 函數
function myLoop(i) { return Promise.delay(1000) .then(function() { if (i > 0) { alert('hello'); return myLoop(i -= 1); } }); } myLoop(3);
<script src="//cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.4/bluebird.min.js"></script>
這是我用於遍歷數組的函數: oop
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); } }
您能夠這樣使用它: this
loopOnArrayWithDelay(YourArray, 1000, 0, function(e, i){ //Do something with item }, function(i){ //Do something once loop has completed }
在ES6(ECMAScript 2015)中,您能夠使用生成器和間隔來進行延遲迭代。 spa
生成器是ECMAScript 6的新功能,能夠暫停和恢復。 調用genFunc不會執行它。 相反,它返回一個所謂的生成器對象,使咱們能夠控制genFunc的執行。 genFunc()最初在其主體的開頭暫停。 方法genObj.next()繼續執行genFunc,直到下一個屈服爲止。 (探索ES6) prototype
代碼示例:
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,那是實現延遲循環的最優雅的方法(我認爲)。