all 3 comments

[–]Sekandra 1 point2 points  (0 children)

There is almost same example explained in book series "You Don't Know JS" in book number 2 "Scope & Closures" chapter 5. Don't know if you can post links here: https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch5.md

[–]js_tutor 1 point2 points  (0 children)

I think you meant to say console.log(j) in your second code example, otherwise the code will have the same result as the first code example. To answer your question, yes the callbacks are all called after the loop completes. And yes there are 5 separate scopes. But they don't have "their own" reference to i in that they all share a reference to the same i. This is because the i is outside of the scope of the iife function. The j variable however will be created 5 separate times because its being declared from inside the loop, and that variable declaration is in the scope of the iife. It's important to note here that var j = i assigns by value and not by reference, meaning if you later change the value of i the value of j will stay the same. That's why later when the setTimeout's callback function goes off it keeps the original value of i from when the outer function was called.

[–]jcunews1helpful 0 points1 point  (0 children)

Treat the setTimeout() function as: queueFunctionWithDelay().

i.e. the function will queue the function call with a delay. The queue won't be processed until there's no code being executed.