Course contentsShow
← JavaScript
Lesson 1208 of 2,72327. The Event LoopFree lesson

Nested setTimeout and Throttling

Learn how browsers throttle nested setTimeout calls and the impact on recursive scheduling patterns.

Nested setTimeout and Throttling

You'll learn how browsers automatically throttle nested setTimeout calls to conserve resources and what that means for recursive timing patterns.

What Is Nested setTimeout?

A "nested" setTimeout happens when you schedule a new timer inside the callback of a previous timer. This creates a chain of timeouts, commonly used for repeated tasks or polling:

function repeatTask() {
  console.log('Running...');
  setTimeout(repeatTask, 100); // nested setTimeout
}
repeatTask();

The Throttling Rule

Browsers enforce a minimum delay of 4ms on nested setTimeout calls after the fifth nested level. Even if you specify setTimeout(fn, 0), the browser clamps it to 4ms once you've nested deeply enough.

This prevents runaway scripts from hogging CPU resources. The exact threshold varies slightly between browsers, but the HTML spec mandates this behavior after the fourth nesting level.

Why It Matters for Recursive Scheduling

If you're using nested setTimeout to create a "loop" that should run as fast as possible, understand that after a few iterations, you'll be throttled to ~250 ticks per second (1000ms / 4ms) maximum.

This is different from a single setTimeout(fn, 0) call, which runs once without throttling. It's the nesting depth that triggers the clamp.

Example Impact

let count = 0;
function tick() {
  count++;
  if (count < 10) {
    setTimeout(tick, 0); // After 5th call, clamped to 4ms
  }
}
tick();

The first few calls happen quickly, but after the fifth nested level, each iteration waits at least 4ms.

Key Takeaway: Browsers throttle nested setTimeout calls to a 4ms minimum after the fifth nesting level to prevent CPU abuse, affecting recursive scheduling patterns that rely on minimal delays.