ajax333221
ajax333221

Reputation: 11754

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?

Upvotes: 2

Views: 4529

Answers (5)

Gunasekaran
Gunasekaran

Reputation: 1

try this it will definitely help who all are think how to make it work wait property inside For Loop... try this code in this URL http://www.shopjustice.com/the-collections/C-10329.

var var2;
var tmp;
var evt;
var i=0;
var res = document.getElementsByClassName('mar-plp-filter-content nav nav--stacked')[0].children.length;
tmp = document.getElementsByClassName('mar-plp-filter-content nav nav--stacked')[0].children;
function myfunc()
{
if(i<res)
{
var2 = tmp[i].getElementsByTagName("span")[0].getElementsByClassName("inverted")[0];
// alert(var2.innerHTML);
var evObj = document.createEvent('MouseEvents');
evObj.initEvent( 'mouseover', true, false );
var2.dispatchEvent(evObj);
var2.style.backgroundColor="GREEN";
i++;
setTimeout(myfunc,3000);
}
};
setTimeout(myfunc,3000);

Upvotes: 0

sg3s
sg3s

Reputation: 9567

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)

Code

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

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

    setTimeout(action, 1000);
})();

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

Upvotes: 9

Maz
Maz

Reputation: 3375

The 10 timeouts are all based on the time that setTimeout() is called. So, they are all triggered at the same time.

for (var i=0; i < 10; i++) {
    (function(idx){
        setTimeout(function(){
            document.write(idx+"<br/>");
        },1000*idx);
    })(i);
};

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359786

Classic function-in-a-loop problem. One archetypal solution:

function createCallback(i) {
    return function () {
        writeMsg(i);
    };
}

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

for (var i=0 ; i < 10 ; i++) {
    setTimeout (createCallback(i), 1000*i);
}

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318488

You pass the return value of a function call to setTimeout instead of a function. Try the following code:

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

In case you wonder why the call is wrapped inside an anonymous function: Without that function each setTimeout callback would receive the same i so when the callbacks fire it would always be 10. The anonymous function creates a new i inside that is not connected to the loop variable.

Upvotes: 4

Related Questions