ajax333221 ajax333221 - 1 year ago 67
Javascript Question

Can't manage to sleep inside a loop

I want to pause

1 second
for every time it loops, it is usually easy to do similar pauses on other cases, but when working with loops, it seems it get harder:

for (var i=0 ; i < 10 ; i++) {
document.write (i + "<br>");
// I want to wait 1 second here

This is one example of my thousands failed attempts:

function writeMsg (index) {
document.write (index + "<br>");

for (var i=0 ; i < 10 ; i++) {
setTimeout (writeMsg(i), 1000);

Any ideas of how to get this to work?

Answer Source

This function works more like a normal for loop while it isn't

You need to take into account that a for gets 3 arguments inbetween semicolons.

  1. Before starting (ie var i=0 you define a variable)
  2. A condition before running the code again (ie i < 10 while i is under 10)
  3. An action everytime it finishes the code again (i++ add one to i)


(function() {
    // Define a variable
    var i = 0,
        action = function() {
            // Condition to run again
            if (i < 10) {
                document.write(i + "<br>");

                // Add one to i
                setTimeout(action, 1000);

    setTimeout(action, 1000);

Here is a jsfiddle for this code demonstrating its working: http://jsfiddle.net/sg3s/n9BNQ/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download