Sub topic 1
One Thread, One Thing at a Time
JavaScript code runs on a single thread. At any moment, the engine is executing exactly one piece of your code. This chapter explains what that means, why the language works this way, and the run-to-completion rule that the rest of this tutorial builds on.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript functions and closures
- Callbacks
- Basic Promise usage (
then,catch) andasync/awaitsyntax - Running JavaScript in a browser console or Node.js
What "single-threaded" means
A thread is a sequence of instructions that a processor executes. Languages such as Java or C++ let a program run many threads at once, so two functions can execute in parallel and touch the same data at the same time.
Your JavaScript code gets one thread. The browser or Node.js may use other threads internally for networking, file access, or decoding images. Your own functions never run in parallel with each other on the main thread.
There is a good reason for this. JavaScript was designed to manipulate web pages. If two threads could edit the same DOM element at once, every script would need locks to avoid corrupting the page. A single thread removes that whole class of bugs.
Run-to-completion
Run-to-completion is the rule that once a piece of JavaScript starts running, it runs until it finishes. Nothing else interrupts it partway through. That includes other callbacks, timers, click handlers, and network responses.
A "piece" here is one unit of work the engine picks up, such as the main script or a single callback. Other work waits its turn until that unit finishes.
let counter = 0;
function incrementTwice(label) {
const before = counter;
counter = before + 1;
counter = counter + 1;
console.log(label, 'before:', before, 'after:', counter);
}
setTimeout(() => incrementTwice('first'), 0);
setTimeout(() => incrementTwice('second'), 0);
// Output:
// first before: 0 after: 2
// second before: 2 after: 4The second callback never sees counter at 1, because the first callback cannot be paused between its two assignments. In a multi-threaded language, the result would depend on how the threads interleaved.
The cost of the guarantee
Run-to-completion makes reasoning easy, but it has a price. A long-running piece of code holds the thread the whole time. While it runs, the page cannot respond to clicks, repaint, or run any other callback.
How does JavaScript still handle timers, network requests, and user input without blocking? The host environment does the waiting elsewhere and queues your callbacks to run later, one at a time. The rest of this tutorial explains how that queuing works, starting with the call stack.
Common misconceptions
| Belief | Reality |
|---|---|
| `async` functions run on another thread | They run on the same thread; they only pause at `await` |
| A timer callback can interrupt a running loop | It waits until the current code finishes |
| The browser has only one thread | The host uses many threads; your JavaScript code runs on one |
Exercise
A click handler is registered, and the user clicks while a function that takes 3 seconds of pure computation is running. When does the click handler run, and why?
Show answer
It runs only after the 3-second function finishes. Run-to-completion means the running code cannot be interrupted, so the click is recorded and its handler waits its turn on the single thread.
Exercise
Why is a lock or mutex unnecessary to protect a shared variable updated inside a single synchronous JavaScript function?
Show answer
Only one piece of JavaScript code runs at a time on the thread, and each piece runs to completion, so no other code can read or write the variable partway through the function.