I am trying to undrstand the code
for(var i = 0; i < 10; i++) {
setTimeout((function(e) {
return function() {
console.log(e);
}
})(i), 1000)
}
from here http://bonsaiden.github.com/JavaScript-Garden/#function.closures
I understood this method :
for(var i = 0; i < 10; i++) {
(function(e) {
setTimeout(function() {
console.log(e);
}, 1000);
})(i);
}
Can anyone please help me by explaining the first one?
I will try to explain how I understands the first one,
first i is 0,
setTimeout is called,
self calling function "function(e)" is called with i=0,
Im stuck!! what happens when this function returns a function?
OK, here’s the long explanation. Remember that the first parameter to
setTimeout()needs to be a reference to the function that you want executed after the specified delay. The simplest case is to just name a function defined elsewhere:Note there are no parentheses on
someFuncwhen passing it as a parameter tosetTimeoutbecause a reference to the function itself is required. Contrast with:With parenthese it calls
someFunc()and passes its return value tosetTimeout. But my definition ofsomeFunc()above doesn’t explictly return a value, so it implicitly returnsundefined– which is like sayingsetTimeout(undefined, 100).But it would work if changed
someFunc()to return a function instead of returningundefined:So now (at last) we come to the code from your question:
Instead of referencing a function by name and calling it as
someFunc(i)it defines an anonymous function and calls it immediately as(function(e) {})(i). That anonymous function returns another function and it is that returned function that becomes the actual parameter tosetTimeout(). When the time is up it is that returned function that will be executed. Because the (inner) function being returned is defined in the scope of the (outer) anonymous function it has access to theeparameter.