"Could you check the updated question by indicating where im messed up?
OK, here is a long explanation. Remember that the first setTimeout() parameter must be a reference to the function that you want to execute after the specified delay. The simplest case is simply to name the function defined elsewhere:
function someFunc() { console.log("In someFunc"); } setTimeout(someFunc, 100);
Note that in someFunc there are no brackets when passed as the setTimeout parameter, because a link to this function is required. Contrast:
setTimeout(someFunc(), 100);
Using parenthese, it calls someFunc() and passes its return value to setTimeout . But my definition of someFunc() above does not explicitly return a value, so it implicitly returns undefined - it's like the expression setTimeout(undefined, 100) .
But this will work if you change someFunc() to return a function instead of returning undefined :
function someFunc() { return function() { console.log("In the function returned from someFunc"); }; }
So, now (finally) we get to the code from your question:
setTimeout((function(e) { return function() { console.log(e); } })(i), 1000)
Instead of referencing a function by name and calling it as someFunc(i) , it defines an anonymous function and immediately calls it as (function(e) {})(i) . This anonymous function returns another function, and this return function becomes the actual setTimeout() parameter. When time runs out, this is the return function to be executed. Since the returned (internal) function is defined in the scope of the (external) anonymous function, it has access to the parameter e .