Skip to the page

JavaScript cost and the main thread · senior

Long tasks and yielding to the main thread

A long task is any main-thread task over 50 ms; while it runs the browser cannot respond or paint, so you break work into chunks and yield between them with scheduler.yield() (with a setTimeout fallback), doing the user-visible update first.

The notes

What you must know

  • The main thread runs one task at a time, to completion. Input handling, rendering and your JS all share it.
  • Long task = over 50 ms. The part above 50 ms is its blocking time. Long tasks cause input delay (INP) and late paints.
  • Yield = end the current task so the browser can handle input and paint, then continue later. await scheduler.yield() continues your work before other queued tasks; setTimeout(0) puts the rest at the END of the task queue.
  • scheduler.yield() is in Chromium (129+) and Firefox (142+) but was still not in Safari as of mid-2026: feature-detect and fall back to a setTimeout promise.
  • Microtasks (await Promise.resolve(), queueMicrotask) do NOT yield: the browser cannot paint or handle input until the microtask queue is empty.
  • Batch: do not yield after every tiny item; yield when about 50 ms has passed since the last yield.
  • Long Animation Frames (LoAF, Chrome 123+) report frames delayed over 50 ms with script attribution, which is better than the old Long Tasks API for finding INP culprits. isInputPending() is no longer recommended.

The red pen

Common traps: mistake → fix

  • Mistake: "async functions run in the background"

    Fix: async code still runs on the main thread; only the waiting is non-blocking.

  • Mistake: "await Promise.resolve() lets the browser breathe"

    Fix: microtasks run before rendering and input; use scheduler.yield() or setTimeout.

  • Mistake: "Yield after every single item"

    Fix: yielding has overhead; yield on a time budget.

  • Mistake: "Web workers fix every long task"

    Fix: workers cannot touch the DOM; rendering and React work stay on the main thread.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is a long task and why 50 ms?
  2. How do you break up a long task? Compare setTimeout and scheduler.yield().
  3. Why does awaiting a resolved promise not help the browser paint?
  4. A click handler sorts 20,000 rows and re-renders. Show how you would restructure it for a good INP.
  5. How do you find which script caused long frames in production?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview