Sub topic 1
One Thread, One Thing at a Time
Prerequisites
This chapter assumes you know JavaScript functions and closures, callbacks, and basic Promise and async/await syntax. You should also be able to run code in a browser console or in Node.js.
One Thread, One Thing at a Time
A JavaScript engine runs your code on a single thread. At any moment, exactly one piece of JavaScript is executing. JavaScript also follows run-to-completion: once a function starts, nothing else interrupts it. No other callback can run in the middle of it. Each function finishes before the engine runs any other queued code.
This means you never get data races between two callbacks. The cost is that a slow function freezes everything else until it returns.
The Call Stack
The call stack is the engine's record of which functions are currently running. A call pushes a frame onto the stack, and a return pops it off. When the stack is empty, no JavaScript is running, and the engine is free to start new work.
Where Asynchronous Work Actually Happens: Host APIs
The engine itself has no timers, network access, or file system. Those features come from the host environment. In a browser, they are Web APIs such as setTimeout, fetch, and DOM events. In Node.js, they are Node.js APIs such as fs and net. When you call setTimeout, the host starts the timer outside the JavaScript thread, and your function returns at once.
The Task Queue
When host work finishes (the timer expires or the data arrives), the host does not call your callback directly. It puts the callback into a task queue. A task is a unit of work that waits there until the stack is empty.
One Turn of the Event Loop
The event loop repeats a simple cycle:
- Wait until the call stack is empty.
- Take the oldest task from the task queue.
- Run it to completion.
- Repeat.
function greet() {
console.log('hello');
}
console.log('start');
setTimeout(greet, 0);
console.log('end');
// Output: start, end, helloThe timer expires almost immediately, but greet has to wait in the queue until the script finishes and the stack is empty.
Exercise
A click handler takes 3 seconds to run. A timer set for 100 ms expires while the handler is running. When does the timer callback run, and why?
Show answer
It runs only after the click handler returns and the call stack is empty. Run-to-completion means nothing can interrupt the handler, so the expired timer's callback waits in the task queue until the event loop can pick it up.