Reputation:
I wonder how the event-loop works in javascript, I am using node.js but I guess that the same question apply to browsers.
I have some async call (let's say setTimeout
or $.ajax
or fs.readFile
)
and after a while the event-loop executes the callback
now when the callback
is getting executed, what happens behind the scene?
Does the it revive the stack that it used when it invoked the async stuff?
In practice what is the context/this that the callback is living in? and how does it work?
edit: thanks, I see.. just one more issue, how does the event loop "remembers" the scope of a callback?
Upvotes: 11
Views: 1646
Reputation: 5437
There is a nice tool called Javascript Loupe created by Philip Roberts that will help you understand how javascript's call stack/event and loop/callback intereact with each other.Write some piece of javascript code in the editor and try to run it.
Upvotes: 0
Reputation: 12422
JavaScript uses function scoping, the scoping rules are the same in all JS environments. As Nican mentioned understanding closure is important to knowing what is available in your current scope.
Basically a function "remembers" the environment in which it was defined. So if you use an inline anonymous function for your callback it will have access to all the variables that are available to its parent function and anything that is passed into it as an argument.
A few resources regarding closures and scope in JavaScript:
Stoyan Stefanov's book Object-Oriented JavaScript does a great job of explaining scoping in JavaScript and how the lexical scoping of functions work (see chapter 4). I'd recommend the book to anyone who is serious about JS programming.
Upvotes: 2