TypeScript · Lesson 10
Event loop & async
How JavaScript runs one thing at a time and still juggles timers, promises and I/O, plus the async patterns built on it (timeouts, debounce, retries, concurrency limits, yielding) and how React and Angular use them.
In short
- One thread: a task runs, then all microtasks, then maybe a paint
- Promise callbacks and code after
awaitare microtasks - An
asyncfunction is synchronous until its firstawait - Await what you start; use
Promise.allfor independent work - Yield with a new task; clean up timers and requests
JavaScript runs your code on one thread. There is no second thread to run a callback while your
function is still running. Everything async (timers, promises, fetch, clicks) is just a callback
that waits in a queue until the thread is free. The event loop decides what runs next.
Most async bugs come from a wrong picture of that order: a state update that "hasn't happened yet", a stale response overwriting a fresh one, a timer that fires after the component is gone, a page that freezes during a big loop. This lesson builds the right picture, then the exercises turn it into tools you'll use at work.
Every TypeScript snippet below has a ▶ Try button. Predict the output first, then run it. The lab waits for pending timers before it stops, as Node does before exiting, so you see output from timers and promises too.
The model: one stack, two queues
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
// A D C B
What happens:
- The script itself is a task. It runs to completion on the call stack: it logs
A, schedules a timer, queues a promise callback, and logsD. - When the stack is empty, the loop runs every microtask in the queue:
C. - Only then does it take the next task: the timer,
B.
| Queue | What goes in | When it runs |
|---|---|---|
| Task queue (macrotasks) | setTimeout/setInterval callbacks, I/O and network callbacks, UI events (click, input), MessageChannel messages | one task per turn of the loop |
| Microtask queue | promise callbacks (then/catch/finally), code after await, queueMicrotask, MutationObserver | after the current task, until the queue is empty |
One turn of the loop: run one task → run all microtasks → (browser) maybe render a frame → next task.
Two consequences you'll meet constantly:
- A promise callback always runs before a timer that was due at the same time, even
setTimeout(fn, 0). - Nothing can interrupt running code. A loop that takes 2 seconds blocks clicks, rendering and every timer for 2 seconds.
Promises: the executor is synchronous, callbacks never are
console.log('1 start');
const p = new Promise<string>((resolve) => {
console.log('2 executor runs immediately');
resolve('done');
console.log('3 still running after resolve');
});
p.then((v) => console.log('5 then:', v));
console.log('4 end of script');
- The function you pass to
new Promiseruns right away, synchronously. resolvedoesn't call anything. It marks the promise as fulfilled and queues the callbacks.- A
.thencallback is always a microtask, even when the promise is already resolved. SoPromise.resolve(x).then(f)never callsfbefore the current code finishes. That guarantee is what makes promise code predictable. - A promise settles once. Later calls to
resolveorrejectare ignored. ThewithTimeoutand combinator exercises rely on this.
Every .then in a chain is another hop through the microtask queue, so two independent chains interleave:
Promise.resolve().then(() => console.log('a1')).then(() => console.log('a2'));
Promise.resolve().then(() => console.log('b1')).then(() => console.log('b2'));
// a1 b1 a2 b2
async/await is promises with nicer syntax
async function loadUser() {
console.log('2 loadUser starts (synchronously)');
await null; // pauses here; the rest is a microtask
console.log('4 after await');
return 'ann';
}
console.log('1 before');
loadUser().then((name) => console.log('5 got', name));
console.log('3 caller keeps going');
- An
asyncfunction runs synchronously until its firstawait. Then it returns a pending promise to the caller. - The code after
awaitis a continuation, queued as a microtask when the awaited promise settles.awaiton a plain value still pauses until the next microtask. return xfulfils the function's promise.throw erejects it.try/catcharoundawaitcatches rejections, but only for promises you actuallyawait:
async function save(): Promise<void> {
throw new Error('disk full');
}
async function onSubmit() {
try {
await save(); // without `await`, the catch below never runs and the rejection is unhandled
console.log('saved');
} catch (e) {
console.log('could not save:', (e as Error).message);
}
}
onSubmit();
A floating promise is a promise nobody awaits or catches. If it rejects, Node logs an unhandled
rejection and, by default, exits the process. Browsers log it to the console. In a serverless function,
the invocation ends when your handler's promise settles, so un-awaited work may never finish. The
@typescript-eslint/no-floating-promises lint rule catches these before the code runs (the compiler
alone doesn't). The lab fails a run
that leaves an unhandled rejection.
Timers
setTimeout(fn, ms)means "queuefnas a task no sooner thanmsfrom now". It can be later, because the thread may be busy, browsers clamp nested timers to 4 ms after five levels, and background tabs throttle timers to once a second or less.- Timers with the same delay fire in the order they were created.
setIntervaldoesn't wait for async work your callback starts. If each run fires a request that takes longer than the interval, requests overlap and pile up. (A slow synchronous callback just delays the next run, and missed ticks are dropped.) A self-reschedulingsetTimeoutstarts the next run only after the previous one has finished.- Keep the id and clear timers you no longer need. A pending timer keeps a Node process alive, and a timer that fires after a component unmounted updates state that no longer exists. The lab warns when a timer is still pending after your code finished.
setTimeout(() => {
console.log('timer 1');
Promise.resolve().then(() => console.log('microtask queued by timer 1'));
}, 0);
setTimeout(() => console.log('timer 2'), 0);
// timer 1, microtask queued by timer 1, timer 2. Microtasks drain between tasks.
Microtask starvation
The loop only moves on when the microtask queue is empty. Microtasks that keep queueing more microtasks starve everything else: no timers, no clicks, no rendering.
let ticks = 0;
setTimeout(() => console.log(`timer finally ran after ${ticks} microtasks`), 0);
function spin() {
ticks++;
if (ticks < 100_000) queueMicrotask(spin);
}
spin();
That's why "yield with await Promise.resolve()" doesn't help a frozen page. To let the browser breathe,
you need a new task: setTimeout(resolve, 0), scheduler.yield() where available, or a Web Worker
for real parallelism. The Yield to the event loop exercise builds this.
Sequential, parallel, limited
const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
const fetchUser = async (id: number) => {
await wait(100);
return { id };
};
async function main() {
let t = Date.now();
for (const id of [1, 2, 3]) await fetchUser(id); // one after another
console.log('sequential ~', Math.round((Date.now() - t) / 100) * 100, 'ms');
t = Date.now();
await Promise.all([1, 2, 3].map(fetchUser)); // all at once
console.log('parallel ~', Math.round((Date.now() - t) / 100) * 100, 'ms');
}
main();
- Use
awaitin a loop only when each step needs the previous result. Promise.allfor independent work. It fails fast on the first rejection.Promise.allSettledwhen partial success is fine.Promise.anyfor the first success.Promise.racefor the first to settle, which mostly means timeouts.- With thousands of items, "all at once" floods the API (most cloud APIs answer
429). Limit the concurrency instead (the mapLimit exercise).
Cancellation: AbortController
Promises can't be cancelled from the outside. The convention across fetch, Node, cloud SDKs and
most libraries is an AbortSignal:
const controller = new AbortController();
const { signal } = controller;
signal.addEventListener('abort', () => console.log('aborted:', (signal.reason as Error).message));
setTimeout(() => controller.abort(new Error('user navigated away')), 10);
// the function doing the work checks the signal, or passes it on (fetch(url, { signal }))
const work = new Promise<void>((resolve, reject) => {
const timer = setTimeout(resolve, 1000);
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(signal.reason);
});
});
work.catch((e: Error) => console.log('work stopped:', e.message));
Handy helpers: signal.throwIfAborted(), AbortSignal.timeout(ms) (a signal that aborts itself) and
AbortSignal.any([a, b]) (aborts when either does). Aborting is cooperative: it only stops work that
listens to the signal. The React & Angular topic's "Latest-only async calls" exercise uses it to drop
stale responses.
In React
- State updates are not immediate.
setCount(count + 1)schedules a re-render.countin the current render keeps its old value. React 18+ (withcreateRoot) batches updates from event handlers, timeouts and promises into one render, so threesetXcalls in asetTimeoutcause one render, not three. - Effects run after the browser paints (
useEffect).useLayoutEffectruns before paint, and you should use it mainly to measure the DOM. - Every effect that starts something async must clean it up. That means clearing timers, aborting fetches and unsubscribing. The cleanup runs before the next effect run and on unmount. In development, Strict Mode runs effects twice to expose missing cleanups.
useEffect(() => {
const id = setInterval(() => setSeconds((s) => s + 1), 1000); // functional update: no stale `seconds`
return () => clearInterval(id);
}, []);
- Stale closures: a callback created during render sees that render's values forever. An interval
that reads
secondsdirectly keeps seeing0. Use functional updates (setSeconds((s) => s + 1)) or a ref. - React's scheduler slices rendering into roughly 5 ms chunks and yields to the browser in between.
That's how
startTransitionkeeps an input responsive. Your own synchronous code isn't sliced.
In Angular
- zone.js patches
setTimeout, promises,addEventListenerand XHR, so Angular knows when any async task finishes and then runs change detection. That's why assigning a field inside asetTimeout"just works". The lab's runner tracks timers the same way. - The cost: every timer tick and every event triggers a change detection pass. Run high-frequency or
background work in
ngZone.runOutsideAngular(...). Zoneless change detection with signals (stable since Angular 20.2, and the default for new apps since Angular 21) updates only what changed, without patching anything. - RxJS is the async workhorse.
debounceTime,throttleTime,switchMap(latest only),mergeMap(fn, n)(n at a time),retry({ count, delay }),forkJoin(likePromise.all) andtakeUntilDestroyed()(cleanup) map one-to-one onto this topic's exercises. - An Observable is lazy and can emit many values. A promise is eager and settles once.
firstValueFrom(obs$)turns an Observable into a promise.
Node and the server
Node runs the same model with extra phases (timers, I/O polling, setImmediate's "check" phase) and
one extra, higher-priority queue: process.nextTick callbacks run before promise microtasks. Those two
are Node-only, so they aren't available in the lab, which runs your code in a browser worker. The
lesson for servers is the same as for the UI: one slow synchronous loop blocks every request handled
by that process. Keep request handlers async and short, and move CPU-heavy work to worker_threads,
a queue (a message queue plus a worker) or another service.
F# for comparison
Side note
.NET has a thread pool, so async code can run on several threads at once. F# has two flavours:
let fetchUser (id: int) = async {
do! Async.Sleep 50
return $"user {id}"
}
let job = fetchUser 1 // nothing has started yet: async { } is cold
let users =
[ 1; 2; 3 ]
|> List.map fetchUser
|> Async.Parallel // like Promise.all
|> Async.RunSynchronously
printfn "%A" users
async { }is cold. It's a recipe that only runs when started (Async.RunSynchronously,Async.Start), and a cancellation token flows through it automatically.task { }is hot like a JS promise. It starts immediately, and it's what you use when calling .NET libraries that returnTask.let!anddo!areawait.Async.ParallelisPromise.all.Async.Sleepis thesleepfrom the sleep and withTimeout exercise.
The exercises
- One at a time, or all at once:
awaitin a loop versusPromise.all, and when the work really starts. - sleep and withTimeout: timers, settling once, and cleaning up after yourself.
- debounce with cancel and flush: closures over a timer, the core of every search box.
- Typed Promise combinators:
all,allSettledandanyfrom scratch, with tuple types. - Retry with exponential backoff:
async/awaitloops, abortable waits and resilient calls to cloud services. - mapLimit: a worker pool that keeps N requests in flight.
- Yield to the event loop: chunk long work so the page stays responsive.
Next, the Advanced async TypeScript topic covers typing async code, async iterators, race conditions,
using/await using, single-flight caching, backpressure and structured concurrency.
Practise this lesson
In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app