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?
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.
@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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With