How do I bind (or pass a value) to a callback at the time the callback function is passed to the caller?
For instance:
function callbackTest() {
for(i=0; i<3; i++){
setTimeout(function(){
console.log("Iteration number ", i);
}.bind(i), i*1000);
}
}
callbackTest();
Results in:
$ node callback-with-bind.js
Iteration number 3
Iteration number 3
Iteration number 3
I would expect the binding to happen at the time the callback is passed to the caller. But no.
How do I do it?
In my actual application, the caller passes another param to my callback, so I can't simply pass i as a param.
function callbackTest() {
for(i=0; i<3; i++){
setTimeout(function(myParam){
console.log("Iteration number ", i);
}.bind(i), i*1000);
}
}
callbackTest();