Caedan Lavender
Caedan Lavender

Reputation: 354

Delayed 'for loop' in javascript

I have a delayed loop working that displays the numbers 0-3 with a 1 second delay, but I want it to then start this process all over again.

I tried putting the whole code into a while loop with x<99 (something that will never occur therefore making the loop repeat forever) This doesn't seem to be working

Here is the code:

sequence=["0","1","2","3"];

while (x<99) {
x=-1;
(function myLoop (i) {          
   setTimeout(function () {   
   x++;
   document.write(sequence[x] + "<br/>");
   if (--i) myLoop(i);  
  }, 1000)
  })(4); 
}

Here is a code-pen link

Can someone please help?

Thanks

Upvotes: 0

Views: 110

Answers (2)

Felix Kling
Felix Kling

Reputation: 816334

A loop won't work in this case. There are multiple ways to do this. One would be to call setTimeout "recursively", increasing the index at each call.

var sequence=["0","1","2","3"];

(function() { // some boilerplate code to keep `i` private
    var i = 0; // running index
    (function run() {
        console.log(sequence[i]);
        i = (i+1) % sequence.length; // increase `i` and wrap around
        setTimeout(run, 1000); // next iteration
    }());
}());

Upvotes: 4

Oscar
Oscar

Reputation: 13960

setInterval() comes to rescue:

"Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function."

https://developer.mozilla.org/en/docs/DOM/window.setInterval

Upvotes: 1

Related Questions