April 18, 2012
How to pass variable to anonymous function
Question by alexeyb
I want to pass variable setTimeout
function and do something with that. When I alert value of i
it shows me numbers that i did not expected. What i m doing wrong? I want log values from 1 till 8.
var end=8;
for (var i = 1; i < end; i ++) {
setTimeout(function (i) {
console.log(i);
}, 800);
}
Answer by Starx
The main reason for this to not to work, is because, of the setTimeout
which is set to run after 800
and the scope of i
.
By the time it executes which the value of i
will already have changed. Thus no definitive result could be received. Just like TJ said, the way to work this around is through a handler function.
function handler( var1) {
return function() {
console.log(var1);
}
}
var end = 8;
for (var i = 1; i < end; i++) {
setTimeout(handler(i), 800);
}