How to save a variable value in closure

I need to create several javascript functions with a static id inside, so the function itself knows what data to process.

Here is the code:

(function(){ function log(s){ if(console && console.log) console.log(s); else alert(s); } var i = 10; while (i--){ window.setTimeout(function(){ // i need i to be 10, 9, 8... here not -1 log(i); },500); } })(); 

The problem is that i is always updated in a loop, and I need to prevent this.

Thank you in advance for your help, comments or advice!

+4
source share
3 answers

A slightly better approach to using the immediately called function in each iteration is for the log() function to return the function.

 (function(){ function log(s){ return function() { if(console && console.log) console.log(s); else alert(s); }; } var i = 10; while (i--){ window.setTimeout( log( i ),500 ); } })(); 

The overall result is that you create fewer function objects.

If you want calls to be made at intervals, use setInterval() or change this:

 window.setTimeout( log( i ), 500 ); 

:

 window.setTimeout( log( i ), i * 500 ); 
+2
source

Just create a function and call it.

 while (i--) { (function(i) { // use i here })(i); } 
+3
source
 (function(){ function log(s){ if(console && console.log) console.log(s); else alert(s); } var i = 10; while (i--){ (function() { // start anon func var copy = i; // copy loop variable window.setTimeout(function(){ log(copy); // refer to copy },500); })(); // end anon func and call it immediately } })(); 
+3
source

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


All Articles