Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท JavaScript Performance

The Main Thread and Long Tasks

Learn why one slow function freezes a page, how to spot long tasks over 50 ms, and how to break up work so clicks and typing stay responsive.

A browser tab does most of its work on a single thread: the main thread. It runs your JavaScript, calculates styles, lays out boxes, paints pixels and handles clicks and key presses, one job at a time. While it is busy with one job, every other job waits in a queue.

That is why a slow function does not just make itself slow. It makes the whole page feel broken: buttons do not react, text typed into an input appears late, animations stutter. In this lesson you will learn what a long task is, how to measure it, and the main technique for fixing it: doing less work per turn.

Tasks and the event loop

The browser runs your code in tasks. A click handler is one task, a setTimeout callback is another, a chunk of parsing is another. Between tasks the browser may render a new frame or process input. If a task never ends quickly, the browser cannot do either.

flowchart LR
  A["Click handler<br/>(5 ms)"] --> B["Render frame"]
  B --> C["Big loop<br/>(300 ms)"]
  C --> D["User taps a button"]
  D -.->|"waits 300 ms"| E["Handler finally runs"]

A 300 ms task blocks input: the tap is only handled after the task finishes.

A task that runs for more than 50 milliseconds is called a long task. The number comes from the RAIL model: if the browser answers input within 100 ms, users feel the response is instant. Since a long task may already be running when the click arrives, you must keep tasks short enough that the remaining wait plus your handler fits in that budget. The newer Interaction to Next Paint (INP) metric measures exactly this.

Long tasks are about main-thread time, not about network time. A page can download in 200 ms and still be unusable for two seconds if its scripts keep the thread busy.

Feeling a long task

Run the loop below. It blocks the thread for about 300 ms, then reports whether it really took that long. On a real page, nothing could be clicked during that time.

JS A blocking loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real long tasks are rarely a while loop on purpose. They come from parsing a huge JSON response, rendering a list of 5,000 rows, running a big framework update, or running third-party scripts.

Finding long tasks with the browser

Browsers can tell you about long tasks through PerformanceObserver. This code is read-only because a sandboxed preview does not reliably report them, but you can paste it into the DevTools console of any page:

JavaScript
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log(`Long task: ${Math.round(entry.duration)} ms at ${Math.round(entry.startTime)} ms`);
  }
});
observer.observe({ type: "longtask", buffered: true });

The Chrome DevTools Performance panel also draws long tasks with a red corner and shows which function consumed the time. The profiling lesson shows how to read that picture.

Fix 1: do less

The cheapest fix is to remove the work: avoid recalculating something that did not change, skip hidden elements, process only the visible page of data, or cache a result. Always ask "does this need to run at all, and does it need to run now?" before reaching for cleverness.

Fix 2: split the work into chunks

If the work must happen, cut it into small pieces and let the browser breathe between them. The simple pattern is to process a slice, then schedule the rest as a new task.

JS Chunking a big job

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Between chunks the browser can render and handle input, so the page stays alive even though the total work is the same.

Fix 3: yield explicitly

setTimeout(..., 0) works everywhere but may be delayed by the browser's minimum timer clamp, and it puts your continuation at the back of the queue. Newer browsers offer scheduler.yield(), which pauses your function, lets the browser handle higher-priority work such as input, and then resumes your function ahead of other queued tasks.

JavaScript
async function handleClick() {
  updateButtonState();          // the part the user must see right now
  await scheduler.yield();      // let the browser paint and handle input
  await saveToServer();         // less urgent work comes after
}

// Fallback for browsers without scheduler.yield()
const yieldToMain = () =>
  globalThis.scheduler?.yield ? scheduler.yield() : new Promise((r) => setTimeout(r, 0));

A good rule: do the work that changes what the user sees first, then yield, then do bookkeeping such as analytics, caching and logging.

Common mistakes

  • Chunks that are still too big. Measure; aim for chunks that take well under 50 ms on a slow phone, not just on your laptop.
  • Yielding in a hot loop on every iteration. Yielding has a cost. Yield by time budget (for example every 10 ms), not every item.
  • Forgetting that async is not threading. async/await and promises do not move code off the main thread. A heavy synchronous loop inside an async function still blocks. For true parallelism, see Web Workers.
  • Testing only on a fast machine. A phone can be 4 to 6 times slower than a developer laptop. DevTools lets you throttle the CPU to simulate that.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What makes a task a "long task"?

    Long tasks are defined by main-thread duration. Anything over 50 ms can delay input handling.
  2. 2. Why does a long task make buttons feel unresponsive?

    The main thread handles one task at a time, so a click that arrives during a long task is only processed afterward.
  3. 3. Does wrapping a heavy loop in an async function move it off the main thread?

    Promises and async functions only schedule continuations. Parallel work needs a Web Worker.
  4. 4. What does scheduler.yield() do?

    It lets the browser process input and rendering, then continues your function ahead of other queued tasks.

Summary

  • The main thread runs JavaScript, style, layout, paint and input handling, one task at a time.
  • A task longer than 50 ms is a long task and can delay input.
  • First remove unneeded work, then split the rest into chunks, and yield between them.
  • scheduler.yield() is the modern way to yield; setTimeout is the fallback.
  • async does not mean parallel; use workers for that.

Next: Loading Scripts: async, defer and Modules