Skip to content

Synchronous vs Asynchronous

JavaScript runs one piece of code at a time on a single thread. Synchronous code runs line by line, and each line finishes before the next one starts. Asynchronous code starts some work, hands JavaScript a callback to run when the work is done, and lets the program carry on in the meantime.

Timers, network requests, file reads, database calls, user events such as clicks, and promises all work asynchronously. Knowing which kind of code is which explains why a value is sometimes not ready on the line after the call that asked for it.

A synchronous function returns its result before the next line runs:

const addVat = (price) => price * 1.2;
console.log('Before');
const total = addVat(50);
console.log('Total with VAT:', total);
console.log('After');

This prints:

Before
Total with VAT: 60
After

setTimeout asks for a callback to run later and returns at once. Even with a delay of 0, the callback waits until the code that is running now has finished:

let visitors = 10;
setTimeout(() => {
visitors += 1;
console.log('Inside the timer:', visitors);
}, 0);
console.log('After setting the timer:', visitors);

This prints:

After setting the timer: 10
Inside the timer: 11

The last line logs 10, because the timer’s callback has not run yet. Code that needs the new value has to go inside the callback, or wait on a promise.

When the running code finishes, JavaScript’s event loop picks the next callback to run. Promise callbacks wait in a queue of their own, called the microtask queue, which is emptied before the next timer or event callback runs:

console.log('script starts');
setTimeout(() => console.log('timer callback'), 0);
Promise.resolve().then(() => console.log('promise callback'));
console.log('script ends');

This prints:

script starts
script ends
promise callback
timer callback

Event Loops explains the queues in more detail.

A promise is an object that exists from the moment it is created, but its value arrives later. Logging the same promise twice shows the change:

const promise = new Promise((resolve) => setTimeout(resolve, 50, 'done'));
console.log(promise);
setTimeout(() => console.log(promise), 100);

This prints:

Promise { <pending> }
Promise { 'done' }

Node prints promises like this, and browser consoles show the same states in their own format. To use the value, attach a then() callback rather than inspecting the promise, as Promises - Basic Syntax shows.

Pitfall: long synchronous work blocks everything

Section titled “Pitfall: long synchronous work blocks everything”

Because there is one thread, a callback cannot run while synchronous code is still busy. A timer’s delay is the shortest wait, not a promise of when it runs:

const start = Date.now();
setTimeout(() => {
const waited = Date.now() - start >= 200 ? 'at least 200 ms' : 'under 200 ms';
console.log(`The 10 ms timer ran after ${waited}`);
}, 10);
while (Date.now() - start < 200) {
// Keep the thread busy for 200 ms.
}
console.log('Loop finished');

This prints:

Loop finished
The 10 ms timer ran after at least 200 ms

In a browser, the same loop would also freeze the page, because clicks and drawing wait for the thread too. Heavy calculations belong in a Web Worker, or in smaller pieces that let other callbacks run in between.

Steve Griffith covers this topic in his video Understanding Synchronous vs Asynchronous JavaScript.