Async/sync callback
Synchronous callback
Runs immediately, during the call of the main function. That is - in the same call stack (before the current function finishes).
Example:
javascript
function process(callback) {
console.log('Before the callback');
callback(); // runs immediately
console.log('After the callback');
}
process(() => console.log('Synchronous callback'));Output:
javascript
Before the callback
Synchronous callback
After the callbackEverything runs in order, with no delays.
Asynchronous callback
Called later, after the current code finishes - for example, via a timer, after a request, an event, and so on. That is - on the next turn of the event loop.
Example:
javascript
function processAsync(callback) {
console.log('Before the callback');
setTimeout(callback, 0); // runs later
console.log('After the callback');
}
processAsync(() => console.log('Asynchronous callback'));Output:
javascript
Before the callback
After the callback
Asynchronous callbackThe callback does not run right away, but after the call stack becomes free.
In short:
| Type | When it runs | Example |
|---|---|---|
| Synchronous | Immediately, during the call | array.map(fn) |
| Asynchronous | Later, after the main code | setTimeout(fn, 0), fetch().then(fn) |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.