Sub topic 1
One Thread, One Thing at a Time
JavaScript can fetch data, wait on timers, and respond to clicks while it seems to be doing several things at once. In fact the engine runs only one piece of your JavaScript at any moment. Everything later in this tutorial, from promises to Node.js phases, builds on that fact. This chapter covers what "single-threaded" means, what the run-to-completion guarantee promises, and where that guarantee stops.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript functions and closures
- Callbacks, meaning functions passed to other functions to be called later
- Basic Promise usage with
thenandcatch - Basic
async/awaitsyntax - Running snippets in a browser console or with Node.js
You don't need to know anything about queues or the event loop yet. Later chapters introduce those pieces one at a time.
What "Single-Threaded" Means
A thread is one sequence of instructions that a CPU core runs. Languages like Java, C#, and C++ let one program start many threads that share memory and run at the same time. The operating system can pause any thread between two machine instructions and switch to another. This is called preemptive scheduling.
JavaScript works differently. Each JavaScript environment, such as a browser tab, a Node.js process, or a Web Worker, has one thread running your code. The specification calls this environment an agent. Within one agent, two of your functions never run at the same instant.
The JavaScript runtime as a whole does use several threads. The browser or Node.js does network requests, file reads, and timer bookkeeping on other threads. Those threads never run your JavaScript. They only report back when something is ready, and your code then runs on the main thread. The chapter on host APIs covers how this hand-off works.
Run-to-Completion
The single thread comes with a guarantee called run-to-completion. Once a piece of JavaScript starts running (an event handler, a timer callback, or the top level of a script), it runs until it finishes. No other JavaScript can cut in partway through.
let count = 0;
setTimeout(() => {
console.log('timer sees count =', count);
}, 0);
for (let i = 0; i < 1_000_000; i++) {
count++;
}
console.log('loop done, count =', count);
// Output:
// loop done, count = 1000000
// timer sees count = 1000000The timer has a delay of 0 ms, but its callback still can't run in the middle of the loop. The callback waits until the whole script has finished. Then it runs and sees the final value. It can never see a half-updated count like 437,912.
What You Get from the Guarantee
Run-to-completion removes a whole class of bugs from everyday code.
| Concern | Preemptive threads (Java, C++) | JavaScript run-to-completion |
|---|---|---|
| Can another function interrupt mine midway? | Yes, between any two instructions | No, never within synchronous code |
| Need locks to update a shared variable safely? | Usually | No, for ordinary objects |
| Data races on plain variables | Possible | Impossible within one agent |
| Can one long function freeze everything? | No, other threads keep running | Yes, nothing else runs until it ends |
The last row is the cost. The guarantee that protects your variables also means a slow function holds up everything else. In a browser that includes clicks, typing, scrolling, and usually page rendering.
What You Pay: Blocking
This snippet shows the cost. Paste it into a browser console on any page, then try to scroll or click:
const start = Date.now();
while (Date.now() - start < 3000) {
// busy-wait for 3 seconds
}
console.log('done');For three seconds the page ignores you. Your input is still recorded, but the handlers can't run until the loop ends, and then they all run in a burst. If the browser detects code that runs much longer than this, it may offer to stop the page. A Node.js server in the same state stops answering every request at once, not only the slow one. Later chapters show how to split up work like this. For now, remember that each synchronous run should be short.
Where the Guarantee Ends
Run-to-completion applies to a single continuous run of synchronous code. It does not mean an async function runs from start to finish without interruption. This is the most common misreading of the guarantee.
`await` Splits a Function into Pieces
Each await ends the current run. The function pauses, the thread is released, and other code can run. The code after the await resumes later as a new run. Each piece runs to completion, but the function as a whole does not.
That allows logical race conditions without any parallelism:
let balance = 100;
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function withdraw(amount) {
if (balance >= amount) {
await delay(10); // pretend to call a payment service
balance -= amount;
}
}
Promise.all([withdraw(80), withdraw(80)]).then(() => {
console.log('balance:', balance);
});
// Output: balance: -60Both calls check balance before either one subtracts from it. The check and the update fall in different pieces, with an await between them, so the other call's check runs in the gap. The fix is to do the check and the update in the same synchronous piece:
let balance = 100;
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function withdraw(amount) {
if (balance < amount) return false;
balance -= amount; // reserve the money before yielding
try {
await delay(10); // pretend to call a payment service
return true;
} catch (err) {
balance += amount; // undo the reservation on failure
throw err;
}
}
Promise.all([withdraw(80), withdraw(80)]).then((results) => {
console.log(results, 'balance:', balance);
});
// Output: [ true, false ] balance: 20A good rule of thumb: any invariant you rely on has to hold at every await, because other code may run there.
Generators Yield the Same Way
A generator function pauses at each yield and resumes when someone calls next(). Each stretch between yields runs to completion. Like await, yield is a point where you give up control voluntarily. JavaScript never forces a pause on you.
Synchronous Pauses That Aren't Yields
Some calls stop your code without letting other JavaScript run:
alert(),confirm(), andprompt()in browsers block the thread until the user responds. Your code waits, and timers and handlers wait with it. (Some browsers have handled this inconsistently in the past, which is one more reason to avoid these calls.)- Synchronous APIs such as
fs.readFileSyncin Node.js block the thread until the I/O finishes. - A
debuggerbreakpoint freezes execution while you inspect it.
None of these break run-to-completion, because no other JavaScript runs during the pause. They are still blocking, and they hurt responsiveness.
Real Shared Memory
Web Workers and Node.js worker_threads run JavaScript on separate threads, each in its own agent with its own heap. Usually they communicate by copying messages, so the no-data-race property still holds. The exception is SharedArrayBuffer, which lets agents share raw memory. Two agents can then write the same bytes at the same time, and you need Atomics to coordinate them. This is deliberate opt-in parallelism and the only place where ordinary JavaScript has true data races.
A Working Mental Model
Keep this picture in mind for the rest of the tutorial:
- One thread runs your JavaScript.
- Your code runs in discrete pieces. Examples are a script, a callback, or the part of an async function between two awaits.
- Each piece runs to completion before any other piece starts.
- Something decides which piece runs next. That something is the event loop, and the next chapters explain its rules.
Exercises
Exercise
A click handler is registered on a button, and the page then starts a synchronous loop that runs for 2 seconds. The user clicks the button 0.5 seconds into the loop. When does the click handler run, and why?
Show answer
It runs after the loop finishes, about 1.5 seconds after the click. Run-to-completion means the loop can't be interrupted. The browser records the click, but the handler has to wait until the thread is free.
Exercise
What does this code log, and why? let x = 1; setTimeout(() => console.log(x), 0); x = 2; x = 3;
Show answer
It logs 3. The timer callback can't run until the current script finishes, and by then all three assignments are done. The callback reads x at the time it runs, not at the time it was scheduled.
Exercise
An async function reads a cache entry, finds it missing, awaits a fetch, and then writes the result to the cache. Two calls for the same key start back to back. How many fetches happen, and how would you make it one?
Show answer
Two fetches happen, because both calls check the cache before either one reaches the write after its await. To make it one, store something in the cache synchronously before awaiting, for example the pending promise itself (cache.set(key, fetchPromise)). The second call then finds and reuses that promise.