Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.2 — Timers
JavaScript · Example 4 of 4

Nested timers are clamped to 4 ms

After 5 levels of nesting, each 0 ms delay becomes 4 ms. That's why chained setTimeout(fn, 0) is a poor way to schedule many small jobs.

setTimeout runs a function once after a delay and setInterval runs it again and again; both return an id you pass to clearTimeout or clearInterval to cancel, and every delay is a minimum, never an exact time.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write code that logs tick 1, tick 2, tick 3, 100 ms apart, using setInterval, then stops.

02

Write delayLog(message, ms) that logs the message after ms, and returns a function that cancels it. Show it cancelling one message.

Explain it without notes

01

What is the difference between setTimeout and setInterval, and how do you stop each?

02

Why can a timer fire later than its delay? Give at least three reasons.

03

When would you use a repeating setTimeout instead of setInterval?

04

What goes wrong with setTimeout(save(), 500)?

Nested timers are clamped to 4 ms

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Levels: 10
Took at least 15 ms (clamping kicked in)? true