for( var i=0; i<20; i++)
setTimeout(function(){
console.log(">>> "+i);
}, i*100);
So, the code above outputs >>> 19
20 times. To keep i
at it's iteration value I'm using a closure:
for(var i=0; i<20; i++)(function(i){
setTimeout(function(){
console.log(">>> "+i);
}, i*100);
}(i));
What's the problem? The problem is loop control statements, continue;
I can do with return;
but for those times when I need break;
code gets counter-intuitive when others try to read it.
So what can I do?
How about this?
for (var i = 0; i < 20; i++) {
var action = (function(i){
setTimeout(function(){
console.log(">>> "+i);
}, i*100);
// break => return false
// continue => return anything (e.g. true)
// default => return nothing
return false;
})(i);
if (action !== undefined) {
if (!action) {
break;
}
else {
continue;
}
}
}
EDIT:
Added "support" for continue statement. This now works somehow like the jQuery.each()
loop.
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