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.
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.