当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - javascript loops with delay between iterations using while

问题描述:

I need this loop to run forever, a while loop, checking the status of something every ten seconds. So, a for loop is not part of the real solution - but I am using a for loop in this example to avoid hanging the browser.

How can this code be structured with an outer while loop, and with a five-second delay between each loop iteration and a 3-second delay each time the waitx function is called.

The desired output is:

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);

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div></div>

网友答案:

Sounds like you're looking for a function that calls itself over and over again

(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));
网友答案:

/*
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);
分享给朋友:
您可能感兴趣的文章:
随机阅读: