0

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

1
  • you may have a look here Commented Nov 19, 2016 at 17:42

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.