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); }
source share