Skip to content

Instantly share code, notes, and snippets.

@thyrlian
Last active April 28, 2018 09:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thyrlian/bee4fa66015f2ec0d15b8f5069c208c6 to your computer and use it in GitHub Desktop.
Save thyrlian/bee4fa66015f2ec0d15b8f5069c208c6 to your computer and use it in GitHub Desktop.
JavaScript Event Loop

Note-taking for What the heck is the event loop anyway? by Philip Roberts.

JavaScript: a single-threaded, non-blocking, asynchronous, concurrent language.

JavaScript has a call stack, an event loop, a callback queue, some other APIs and stuff.

V8 has a call stack and a heap.

DOM, Ajax (XMLHttpRequest), setTimeout are from Web APIs provided by browser.

JavaScript Runtime = JavaScript Engine + Web APIs + Callback Queue

one thread = one call stack = one thing at a time

If we step into a function, we push something onto the stack (top); if we return from a function, we pop up off the stack (top).

setTimeout is not a guaranteed time to execution, it's a minimum time to execution. setTimeout 0 doesn't run the code immediately, it runs the code next-ish.

setTimeout

Code Snippet:

function sleep(milliseconds, doSth) {
  var start = new Date().getTime();
  console.log('Sleep now...');
  while (new Date().getTime() < start + milliseconds);
  doSth();
}

console.log('Hello');

setTimeout(function() {
  console.log('----- Timeout is over! -----');
}, 0);

console.log('Here');

sleep(5000, function() {
  console.log('Doing something, everyone has to wait for me!');
});

console.log('There');

Console Output:

# Hello
# Here
# Sleep now...
# Doing something, everyone has to wait for me!
# There
# ----- Timeout is over! -----

The browser repaints the screen every 16.67 milliseconds (which is 60 frames a second), it simply adds a render call into render queue. It can't do a render if there is code on the stack, the render call is just like a callback, it has to wait until the stack is clear, except the render has a higher priority than callback. Render also has a chance to do its job between each callback. That's why don't put slow code on the stack which will block the render, cause stuttering UI.

Sometimes the code doesn't block the stack, but it floods the queue, queues up a ton of callbacks. In this case, you should debounce the events.

View raw

(Sorry about that, but we can’t show files that are this big right now.)

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