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.

10 min read

In short

  • One thread: a task runs, then all microtasks, then maybe a paint
  • Promise callbacks and code after await are microtasks
  • An async function is synchronous until its first await
  • Await what you start; use Promise.all for 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

▶ Try
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
// A D C B

What happens:

  1. 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 logs D.
  2. When the stack is empty, the loop runs every microtask in the queue: C.
  3. Only then does it take the next task: the timer, B.
QueueWhat goes inWhen it runs
Task queue (macrotasks)setTimeout/setInterval callbacks, I/O and network callbacks, UI events (click, input), MessageChannel messagesone task per turn of the loop
Microtask queuepromise callbacks (then/catch/finally), code after await, queueMicrotask, MutationObserverafter 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

▶ Try
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 Promise runs right away, synchronously.
  • resolve doesn't call anything. It marks the promise as fulfilled and queues the callbacks.
  • A .then callback is always a microtask, even when the promise is already resolved. So Promise.resolve(x).then(f) never calls f before the current code finishes. That guarantee is what makes promise code predictable.
  • A promise settles once. Later calls to resolve or reject are ignored. The withTimeout and combinator exercises rely on this.

Every .then in a chain is another hop through the microtask queue, so two independent chains interleave:

▶ Try
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

▶ Try
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 async function runs synchronously until its first await. Then it returns a pending promise to the caller.
  • The code after await is a continuation, queued as a microtask when the awaited promise settles. await on a plain value still pauses until the next microtask.
  • return x fulfils the function's promise. throw e rejects it. try/catch around await catches rejections, but only for promises you actually await:
▶ Try
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 "queue fn as a task no sooner than ms from 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.
  • setInterval doesn'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-rescheduling setTimeout starts 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.
▶ Try
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.

▶ Try
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

▶ Try
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 await in a loop only when each step needs the previous result.
  • Promise.all for independent work. It fails fast on the first rejection.
  • Promise.allSettled when partial success is fine. Promise.any for the first success. Promise.race for 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:

▶ Try
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. count in the current render keeps its old value. React 18+ (with createRoot) batches updates from event handlers, timeouts and promises into one render, so three setX calls in a setTimeout cause one render, not three.
  • Effects run after the browser paints (useEffect). useLayoutEffect runs 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.
▶ Try
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 seconds directly keeps seeing 0. 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 startTransition keeps an input responsive. Your own synchronous code isn't sliced.

In Angular

  • zone.js patches setTimeout, promises, addEventListener and XHR, so Angular knows when any async task finishes and then runs change detection. That's why assigning a field inside a setTimeout "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 (like Promise.all) and takeUntilDestroyed() (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:

▶ Try
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 return Task.
  • let! and do! are await. Async.Parallel is Promise.all. Async.Sleep is the sleep from the sleep and withTimeout exercise.

The exercises

  1. One at a time, or all at once: await in a loop versus Promise.all, and when the work really starts.
  2. sleep and withTimeout: timers, settling once, and cleaning up after yourself.
  3. debounce with cancel and flush: closures over a timer, the core of every search box.
  4. Typed Promise combinators: all, allSettled and any from scratch, with tuple types.
  5. Retry with exponential backoff: async/await loops, abortable waits and resilient calls to cloud services.
  6. mapLimit: a worker pool that keeps N requests in flight.
  7. 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