Skip to content
jshacks.dev
Async

Synchronous vs Asynchronous Code: What Blocks and What Does Not

Compare synchronous and asynchronous code in JavaScript, see which operations block the thread, and learn how to spot a blocking call before it hurts.

6 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the JavaScript, TypeScript, Node.js, Vite and npm logos.

A server that handles one request in 5 ms can still stall every other request for a full second, if a single handler calls one synchronous function in the wrong place. The difference between synchronous and asynchronous code is not style. It decides whether the thread is held. This post compares the two on Node.js 24 and in browsers: what blocks, what does not, how the Sync suffix in Node.js signals the difference, which everyday operations are secretly synchronous, and how to measure a blocked thread with an event loop timer. It ends with a short procedure for deciding which form to use.

The difference in one experiment

A timer that fires every 10 ms shows whether the thread is free. Run a synchronous call beside it and the ticks stop.

JavaScript
import { readFileSync } from "node:fs";
import { readFile } from "node:fs/promises";

let ticks = 0;
const timer = setInterval(() => ticks++, 10);

await readFile("package.json", "utf8");
const afterAsync = ticks;

readFileSync("package.json", "utf8");
const afterSync = ticks;

clearInterval(timer);
console.log("ticks after async read:", afterAsync >= 0);
console.log("ticks changed during sync read:", afterSync !== afterAsync);
Text
ticks after async read: true
ticks changed during sync read: false

The readFileSync call cannot let a tick through, because no timer callback can run while that call holds the stack. The count read right after it equals the count read right before it. The asynchronous read, by contrast, gives the loop a chance to run other work. For one small file the difference is invisible. For a slow disk, a network share or a large file, it is the difference between a responsive process and a frozen one. The script assumes a package.json in the working directory.

What blocks

A call blocks when the thread cannot do anything else until it returns. Three groups cause it.

  1. Synchronous APIs. In Node.js, functions ending in Sync, such as readFileSync, execSync and pbkdf2Sync, run to completion before returning.

  2. Heavy computation. A loop over a million items, a large JSON.parse, a regular expression that backtracks. These are synchronous even though no Sync appears in the name.

  3. Waiting by polling. A while loop that checks a flag, because nothing else can set the flag while the loop owns the thread.

JavaScript
let done = false;

setTimeout(() => {
  done = true;
}, 10);

const start = Date.now();

while (!done && Date.now() - start < 50) {
  // spins until the 50 ms safety limit
}

console.log("done flag was set:", done);
Text
done flag was set: false

The timer callback could never run, because the loop never yielded. The 50 ms safety limit stopped it. Without that limit, this program would spin forever. Polling a variable that only another task can change is always a bug in JavaScript.

What does not block

Anything the runtime does outside your thread and reports back with a callback or a promise. Network requests with fetch, timers, file reads through node:fs/promises, database drivers that use sockets, and child_process.exec all start work and return. The thread continues, and the result arrives as a task later.

JavaScript
console.log("A");

setTimeout(() => console.log("C: timer"), 0);

Promise.resolve().then(() => console.log("B2: microtask"));

console.log("B");
Text
A
B
B2: microtask
C: timer

The synchronous lines A and B run in order. Then the promise callback runs, and then the timer. Asynchronous callbacks always run after the current synchronous code completes, and microtasks run before timers. That ordering is explained in the event loop post.

Secretly synchronous operations

Some operations look harmless and block.

OperationWhy it blocks
JSON.parse(hugeString)Parsing runs on the thread until finished
array.sort() on a large arrayComparison runs in a tight loop
crypto.pbkdf2SyncCPU work, deliberately slow
require() of a large moduleReads and runs it synchronously
for loop over a large collectionNothing yields in the middle
Regular expression with nested quantifiersBacktracking can take exponential time

Notice that none of these are I/O. The word asynchronous suggests the network, but the biggest blockers in real Node.js servers are CPU-bound. A function marked async that does heavy computation still blocks, because async only changes how the result is delivered, not where the work runs.

JavaScript
async function heavy() {
  let sum = 0;
  for (let i = 0; i < 50_000_000; i++) sum += i;
  return sum;
}

const start = Date.now();
let ticked = false;
setTimeout(() => (ticked = true), 0);

const promise = heavy();
console.log("heavy returned a promise, ticked:", ticked);

await promise;
console.log("after await, ticked:", ticked);
Text
heavy returned a promise, ticked: false
after await, ticked: false

The loop ran inside the call to heavy(), before it returned its promise. The timer could not run until the script's current synchronous work was finished, and the await resumes in a microtask, ahead of timers. The second ticked is still false because the timer task has not had a turn yet. This is the case that makes people think async makes a function non-blocking. It does not.

Measuring a blocked thread

Node.js can report how late the event loop is running. perf_hooks.monitorEventLoopDelay records the gap between when a timer should have fired and when it did.

JavaScript
import { monitorEventLoopDelay } from "node:perf_hooks";

const histogram = monitorEventLoopDelay({ resolution: 10 });
histogram.enable();

const start = Date.now();
while (Date.now() - start < 120) {
  // block the thread for 120 ms
}

await new Promise((resolve) => setTimeout(resolve, 50));
histogram.disable();

console.log("max delay above 100 ms:", histogram.max / 1e6 > 100);
Text
max delay above 100 ms: true

The histogram values are in nanoseconds, so dividing by 1e6 gives milliseconds. A max over 100 ms confirms the loop was held for about 120 ms. In production you would record the percentiles, not a single max, and alert when p99 rises. The exact numbers you see will vary with the machine, which is why the example prints a comparison and not the raw value.

A short decision procedure

  1. Does the operation wait on something outside the process, such as the disk, a network or a child process? Use the asynchronous form.

  2. Does it only compute? Keep it synchronous if it is short. If it can take longer than a frame in a browser, or several milliseconds in a server, split it into chunks or move it to a worker.

  3. Is it at startup, before the process serves anyone? A Sync call is fine there. Reading configuration with readFileSync before the server listens blocks nobody.

  4. Is it in a request path or an event handler? Treat any synchronous call as a defect until proven small.

Startup is the one place the rule relaxes, and it is worth stating plainly, because "never use Sync" is advice that people follow into more complicated code with no benefit.

When this does not apply

Command line scripts that do one thing and exit have no other work to starve. A build script that uses readFileSync throughout is simpler than the promise version and not slower in any way that matters. The cost of blocking is paid by whatever else needed the thread, and if nothing else does, nobody pays.

What to do about a blocking call you find

When you do find a blocking call in a hot path, the fix depends on what kind it is. For a Sync I/O function, swap in the promise version and add an await. For CPU work that takes a few milliseconds, leave it alone, because the overhead of moving it elsewhere would cost more than it saves. For CPU work that takes tens of milliseconds or more, break it into chunks and yield between them with setImmediate in Node.js or scheduler.yield in a browser, or hand the job to a worker thread so the main thread stays free for requests and input.

The order of those options matters. Reach for the cheapest one that removes the stall, and measure again with an event loop delay histogram before and after, because intuition about what is slow is wrong often enough to be worth checking.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.