The event loop · core
One thread, run-to-completion and callbacks
JavaScript runs your code on one thread and finishes each piece of work completely before starting the next (run-to-completion); slow work like network requests and timers is handed to the host (browser or Node), which later queues a callback — and callbacks alone lead to nesting, lost errors and inversion of control.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- One call stack per thread (a tab's main thread, or a worker). While it is busy, nothing else on that thread runs: no clicks, no timers, no rendering.
- Run-to-completion: a running function is never interrupted by another JavaScript callback. A busy while loop blocks timers forever.
- Async means 'start now, finish later'. The waiting happens in the host (browser Web APIs, Node's libuv), not on the JavaScript thread; your callback runs on the same thread later.
- Node's error-first callback style: callback(err, data).
- Callback problems: deep nesting (callback hell), error handling at every level, and inversion of control: a library might call you twice, never, or synchronously.
- An API must be always async or always sync. Mixing them (calling back synchronously from a cache, asynchronously otherwise) causes order bugs.
- Promisify wraps a callback API in a promise (Node has util.promisify).
The red pen
Common traps: mistake → fix
Mistake: setTimeout(fn, 0) runs immediately
Fix: it runs after the current task and all microtasks finish.
Mistake: Async code runs on another JavaScript thread
Fix: only the waiting happens elsewhere; callbacks run on the same thread.
Mistake: Every callback is async
Fix: callbacks given to map, forEach or sort run synchronously.
Easy to hard
Questions interviewers ask, easy to hard
- JavaScript is single-threaded. How does it do async work?
- What does run-to-completion mean? What happens with a busy loop and a 10 ms timer?
- What problems do callbacks have?
- Implement promisify.
- Why must an API be always sync or always async?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.