cssyphus
cssyphus

Reputation: 40038

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>

jsFiddle for playing with

Upvotes: 0

Views: 98

Answers (2)

Taplar
Taplar

Reputation: 24965

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

Upvotes: 1

adeneo
adeneo

Reputation: 318202

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

Upvotes: 1

Related Questions