Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: for vs jQuery.each() with time delay

Figure 1

for (var i = Things.length - 1; i >= 0; i--) {
    setTimeout(function(){
        // do something with Things[i]
    }, 200 * i);
};

Figure 2

$(".things").each(function(i,o){
    setTimeout(function(){
        //do something with o
    }, 200 * i);
});

Why does figure 2 work but figure 1 doesn't? Every time I try the first method i always equals -1. What gives?

like image 901
Calvin Avatar asked Jul 11 '26 07:07

Calvin


2 Answers

for (var i = Things.length - 1; i >= 0; i--) {
    (function(i){
        setTimeout(function(){
          // do something with Things[i]
        }, 200 * i);
    })(i)
};

You need to create a scope for i, so it maintains its value. Otherwise it gets updated with the loop.

The reason it works for figure 2 ($.each(function(i,o){...})) is because the anonymous function here is creating a closure for i.

like image 136
ahren Avatar answered Jul 13 '26 23:07

ahren


@ahren answer is ok. I got similar thing without IIF, which could be more simple for someone...

function loop(i) {
// do something with Things[i]
    if(--i>=0) {
        setTimeout(loop, 200*i, i);
    }
}

setTimeout(loop, 200*Things.length, Things.length);
like image 31
Entity Black Avatar answered Jul 14 '26 01:07

Entity Black



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!