0

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

2 Answers 2

4

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
    }());
}());
Sign up to request clarification or add additional context in comments.

4 Comments

@Caedan: You have to look at the console!
@alex23: Yeah I guess setInterval would work equally well. Personally I feel I have more control over the whole process when using setInterval with recursion. I'm also just more used to it (in combination with Ajax calls). I guess it boils down to whether you want to have the code be executed strictly every x seconds or x seconds after the last run. Might make a different in some applications.
@alex23: I read the question as that the process should run forever.
Thanks, i replaced console.log with document.write and it worked perfectly
1

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

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.