How to make anonymous functions local parameters

How to make this javascript alert 0, 1 and 2 instead of 3 3?

var vals = [1, 2, 3]; for(var i = 0; i < vals.length; i++) { window.setTimeout(function() {alert(i);}, 1000); } 

I know the reason why he does this, but I cannot figure out how to pass i an anonymous function.

+6
source share
3 answers

You can wrap this in closure like this:

 var vals = [1, 2, 3]; for(var i = 0; i < vals.length; i++) { (function(num) { window.setTimeout(function() {alert(vals[num]);}, 1000); })(i); } 

Try: http://jsfiddle.net/qgL7h/

+9
source
 var vals = [1, 2, 3]; function makeCallback(i) { return function () {alert(i);}; } for(var i = 0; i < vals.length; i++) { window.setTimeout(makeCallback(i), 1000); } 
+3
source

I don’t have to pass the function, it can be assigned to the local var inside.

 var vals = [1, 2, 3]; for(var i = 0; i < vals.length; i++) { (function() { var num = i window.setTimeout(function() {alert(vals[num]);}, 1000); })(); } 

Requires "function () {block} ()" because Javascript did not have the correct block lexical variables. Recent releases have added "let," which makes this possible:

 var vals = [1, 2, 3]; for(var i = 0; i < vals.length; i++) { let num = i window.setTimeout(function() {alert(vals[num]);}, 1000); } 
0
source

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


All Articles