Skip to content

Instantly share code, notes, and snippets.

@adrianmcli
Created January 6, 2017 20:26
Show Gist options
  • Save adrianmcli/e92d89696646903324449deffc8553b5 to your computer and use it in GitHub Desktop.
Save adrianmcli/e92d89696646903324449deffc8553b5 to your computer and use it in GitHub Desktop.
A simple event loop example. Guess the output (answer in the comments).
var a = "hey";
var cb = function() { console.log(a); }
setTimeout(cb, 1000);
// let's make a delay of 3 seconds
var timestamp = Date.now() + 3000;
while (Date.now() < timestamp);
// now that 3 seconds have passed,
// let's change the value of a
a = "there";
@adrianmcli
Copy link
Author

adrianmcli commented Jan 6, 2017

Answer

It will output "there".

Reason

This is because setTimeout() puts the callback function cb to be executed on the queue. Which means cb can only be executed when the event loop puts it onto the stack, since things in the queue can only be executed by the event loop.

As a rule, the event loop only puts things (from the queue) onto the stack when the stack has been cleared. And since the current stack frame does not pop until after line 12, we are still able to mutate the a, and thus change the behaviour of what is output.

One important thing to note here is that setTimeout() only guarantees a minimum delay time.

More

For more information, watch this video: https://www.youtube.com/watch?v=8aGhZQkoFbQ

This example was inspired by a more complicated example from Daniel Parker's JavaScript with Promises:

var async = true;
var xhr = new XMLHttpRequest();
xhr.open('get', 'data.json', async);
xhr.send();

// Create a three second delay (don't do this in real life)
var timestamp = Date.now() + 3000;
while (Date.now() < timestamp);

// Now that three seconds have passed,
// add a listener to the xhr.load and xhr.error events
function listener() {
   console.log('greetings from listener');
}
xhr.addEventListener('load', listener);
xhr.addEventListener('error', listener);

The question is whether or not the event listeners will ever get triggered by the response?

The correct answer is that they will always get triggered (if there was indeed a response).

Source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment