javascript循环使用while迭代之间的延迟

时间:2016-11-19 17:39:30

标签: javascript jquery

我需要这个循环永远运行,while循环,每隔十秒检查一次事物的状态。因此,for循环不是真正解决方案的一部分 - 但我在此示例中使用for循环以避免挂起浏览器。

如何使用外部while循环构造此代码,并且每次循环迭代与每次调用waitx函数时的3秒延迟之间有5秒的延迟。

所需的输出是:

display loop counter
wait 5 seconds
display curr time
wait 3 seconds
display time diff
(loop) display next loop counter
etc.



//$('body').css('background','wheat'); //test if js is broken 
function waitx(truck){
  console.log(truck);
  $('div').html(truck);
  setTimeout(function(){
    newnow = new Date().getTime();
    var diff = newnow - truck;
    console.log(diff);
    $('div').html(diff); //unwanted - just shows what SHOULD happen below
    return diff;
  },3000);
}

for (var nn=1; nn<6; nn++){
  console.log(nn);
  setTimeout(function(){
    now = new Date().getTime(); //1479575397219
    bonk = waitx(now);
    //$('div').html(bonk + " hello"); //how to get this to work?
  },5000);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div></div>
&#13;
&#13;
&#13;

jsFiddle for playing with

2 个答案:

答案 0 :(得分:1)

听起来你正在寻找一次又一次自我调用的功能

&#13;
&#13;
(function waitx(i) {
    console.log('loop counter : ' + i);
    setTimeout(function() {
    	var now = new Date().getTime();
    	console.log('current time : ' + now);
        
        setTimeout(function() {
            var diff = new Date().getTime() - now;
            console.log('time diff : ' + diff);
            waitx(++i);
        }, 3000)
    },5000);
}(0));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

/*
display loop counter
wait 5 seconds
display curr time
wait 3 seconds
display time diff
(loop) display next loop counter
etc.
*/

(function startLoop(counter) {
  console.log(counter);
  
  setTimeout(function wait5Seconds() {
    console.log(Date.now());
    
    setTimeout(function wait3Seconds() {
      console.log(Date.now());
      startLoop(++counter);
    }, 3000);
  }, 5000);
})(0);