Best way to capture values inside loops
for( var i=0; i<20; i++) setTimeout(function(){ console.log(">>> "+i); }, i*100); So, the code above prints >>> 19 20 times. To save i with the iteration value, I use closure:
for(var i=0; i<20; i++)(function(i){ setTimeout(function(){ console.log(">>> "+i); }, i*100); }(i)); What is the problem? The problem is the loop control statements, continue; I can do with return; but for those cases when I need to break; , the code becomes 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 (eg true) // default => return nothing return false; })(i); if (action !== undefined) { if (!action) { break; } else { continue; } } } EDIT:
Added support to continue. Now it works somehow like a jQuery.each() loop.