>> "+i); }, i*100); So, the code above p...">

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?

+6
source share
2 answers

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.

+3
source

the problem is that the code is actually called after the loop when the variable i is equal to 19. you need to use some local variable. so as not to confuse myself, I suggest using a different name for the close parameter.

By the way, the second version works well

+1
source

Source: https://habr.com/ru/post/920930/


All Articles