JavaScript async callback and scope

asynchronous, callback, javascript, scope

Solution

Create a closure so that the `setTimeout` handler will refer to the closure's local variable (which in this case, we also named `i`), not the `i` from the loop:

for (var i = 0; i < 3; i++) {
    (function (i) {
        console.log(i);
        setTimeout(function () {
            cb(i);
        }, 1000);
    }(i));
}

Problem

Consider the following example: ``` var cb = function (t) { console.log('callback -->' + t); }; for(var i = 0; i<3; i++) { console.log(i); setTimeout(function(){ cb(i); },1000); } ``` Working example at jsfiddle The output of this code snippet is: ``` 0 1 2 callback ---> 3 callback ---> 3 callback ---> 3 ``` Everything works as expected, for loop puts 3 callback calls into the event loop. By the end of the for loop i == 3 and when the callbacks get executed all of them print 3 because they contain the link to the i which is 3. How could this snippet be improved so when the callback gets executed it uses the actual value which was passed to it. The output should be: ``` callback ---> 1 callback ---> 2 callback ---> 3 ``` Thanks in advance.

Original source