11

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?

  • 1
    No. JavaScript does not revive the stack. Read up on how closure works. – Nican Jun 25 '11 at 06:19
  • 1
    This might be of use: (http://stackoverflow.com/questions/183214/javascript-callback-scope). And for a relevant jQuery function: (http://api.jquery.com/jQuery.proxy/) – Doug Owings Jun 25 '11 at 06:40

2 Answers2

2

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.

Useless Code
  • 12,123
  • 5
  • 35
  • 40
  • how does the event loop "remembers" the scope of a callback? –  Jun 25 '11 at 09:06
  • 1
    @browsingLoops: The callback remembers the scope itself. Upon function *definition*, the function inherits the scope chain of the outer function (if present). Have a look at the [specification](http://ecma262-5.com/ELS5_HTML.htm#Section_13). For function declaration it says: *"Return the result of creating a new Function object as specified in 13.2 with parameters specified by `FormalParameterListopt`, and body specified by `FunctionBody`. **Pass in the `VariableEnvironment` of the running execution context as the `Scope`."*** – Felix Kling Jun 25 '11 at 09:08
0

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.

Manish Jangir
  • 5,329
  • 4
  • 42
  • 75