Keeping the page responsive
JavaScript runs one thing at a time. Yet a page can wait for a server, count down a timer and answer a click, all at once. The event loop is how: a queue of work the browser hands back to your code whenever it is free.
One thing at a time
Your code runs on a single call stack. A function is pushed on when it is called and popped off when it returns. While the stack is busy, nothing else of yours runs: not a click handler, not a timer.
console.log('one');
setTimeout(() => console.log('three'), 0);
console.log('two');
// one, two, three
Even with a delay of zero, three comes last. The timer's callback waits in a queue until the stack is empty.
Tasks and microtasks
There are two queues. Timers and events are tasks. Promise callbacks are microtasks, and every microtask runs before the next task does.
That is why a resolved promise's then runs before a setTimeout of zero.
A long loop blocks everything: clicks, timers and screen updates all wait for it. Split heavy work into pieces, or move it off the page's thread.
Points to keep
- checkYour code runs on one call stack, one function at a time.
- checkTimers and events wait in a queue until the stack is empty.
- checkPromise callbacks run before the next timer or event.
- checkKeep long work short, or split it, so the page stays responsive.