Created
January 6, 2017 20:26
-
-
Save adrianmcli/e92d89696646903324449deffc8553b5 to your computer and use it in GitHub Desktop.
A simple event loop example. Guess the output (answer in the comments).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Answer
It will output "there".
Reason
This is because
setTimeout()
puts the callback functioncb
to be executed on the queue. Which meanscb
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:
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