All 28 lessons ▾

Inside JavaScript · Lesson 17 of 28

Why setTimeout Is Never On Time

Updated 16 Nov 2026 · By Akshay, software engineer, India · 9 min read

So setTimeout says five seconds. But sometimes your callback runs after ten! Is setTimeout lying? Now let's find out why it's never exactly on time.

The video for this lesson is coming soon.

A new lesson goes up every day at 11 am. Subscribe on YouTube so you don't miss it.

Got a doubt? Ask in the comments under the video.Subscribe

In one minute
  • setTimeout's delay is a minimum, not exact
  • The callback needs a finished timer and an empty stack
  • A busy main thread makes timers late
  • Rule one: never block the main thread
  • setTimeout 0 runs after the current code
  • Browsers clamp nested and background timers

Part 1The five-second promise

So we've learned how the event loop works. So today, let's use that knowledge to solve a mystery. You write setTimeout with five thousand milliseconds. Will your callback run after exactly five seconds? Most people say yes. But the real answer is, not always. Sometimes it's six seconds, or ten, or even more. So setTimeout has trust issues! Let's see why.

blocked.js
1console.log("Start");2setTimeout(function cb() {3  console.log("Callback");4}, 5000);5console.log("End");6 7// a loop that blocks for 10 seconds8const begin = Date.now();9while (Date.now() - begin < 10000) {}10 11console.log("Loop done");
Output
Start
End
Loop done
Callback

So look at this program. Global is pushed. Line one prints Start. Line two registers cb in the Web APIs, and starts a five second timer. Line five prints End. Now line eight notes the current time, and line nine is a while loop that keeps spinning, doing nothing, until ten seconds have passed. It's blocking the main thread. Five seconds pass. The timer expires, and cb moves into the callback queue. The event loop checks. Is the call stack empty? No! Global is still busy with that loop. So cb waits. And waits. At ten seconds, the loop finally ends. Line eleven prints Loop done. Global is popped, and the stack is empty at last. Now the event loop pushes cb. Line three prints Callback. Ten seconds, not five!

0 s
Start, End, the loop
begins
5 s
timer done: cb waits in
the queue
10 s
loop ends: the stack is
empty
cb runs
five seconds late
expected here

So let's put it on a timeline. At zero seconds, Start and End print, and the loop begins. At five seconds, the timer is done, and that's when we expected the callback. But it can't run. It's stuck in the queue, because the loop is still on the call stack. At ten seconds, the loop ends, and the stack is empty. And only then, the callback actually runs. Five seconds late. So the timer did its job perfectly. It was the busy call stack that made us wait.

REMEMBER THIS
setTimeout'sdelayisa
minimum,notapromise.
the callback also needs an empty call stack
THINK OF IT LIKE THIS
A5pmappointment:you
goinat5onlyifthe
doctorisfree.
a long patient inside means you wait

So remember this. The number you give setTimeout is a minimum. It means, not before this time. It doesn't mean, exactly at this time. The callback needs two things. The timer must be done, and the call stack must be empty. So if the stack is busy, the callback waits, no matter what the timer said. This is how JavaScript's concurrency model works. One call stack, and everything else waits its turn. And it's not just the browser. Node.js works the same way. Its timers are a minimum too, and a busy main thread delays them just the same.

Now think of a doctor's appointment at five pm. Your appointment time is five. But if the patient before you takes an extra hour, you go in at six. Your appointment didn't lie. It just meant, not before five. So setTimeout works exactly the same way. The timer is your appointment, and the call stack is the doctor's room.

Part 2Rule one: don't block

And now this brings us to what I'd call the first rule of JavaScript.

RULE ONE
Neverblockthemain
thread.
one thread runs your code, your clicks and your timers
BUT WHY ONE THREAD?
Onethreadmeansnotwo
piecesofcodeeverfight
overthesamedata.
simple and safe; async APIs do the waiting

Never block the main thread. JavaScript has just one call stack, so that one thread runs your code, handles every click, and every timer callback. Now if you keep it busy for ten seconds, everything waits for ten seconds. Timers run late, buttons stop responding, and the page feels frozen. So keep your functions short, and hand heavy waiting to async APIs, so the call stack stays free. Now you'll also hear senior developers say, don't block the event loop. Same rule, different words.

Now a lot of people ask, why does JavaScript have only one thread? Wouldn't more threads be faster? So here's the beauty of it. With one thread, no two pieces of your code ever run at the same moment, so they can never fight over the same data, or change the page at the same time. That makes JavaScript simple, and safe, and light enough to run in every browser. And the waiting, timers, network calls, and clicks, is done outside, by the browser. So you get async power, without the headaches of many threads.

measure.js
1const start = Date.now();2 3setTimeout(function () {4  console.log("ran after", Date.now() - start, "ms");5}, 100);6 7// heavy work on the main thread8for (let i = 0; i < e9; i++) {}

So want to see trust issues with your own eyes? Try this in your browser's console. We ask setTimeout for one hundred milliseconds, and then run a loop of a billion steps on the main thread. Now look at what it prints. Not one hundred. Something like eight hundred, or even more, depending on your machine. The callback was ready long ago, but the loop held the call stack. So measure it yourself once, and you'll never blindly trust setTimeout again.

HEAVY WORK?
MoveittoaWebWorker:
aseparatethread,sothe
mainonestaysfree.
workers can't touch the page, but they can crunch
numbers

So what if you really do have heavy work, like processing a huge file, or crunching millions of numbers? Browsers give you a way out. It's called a Web Worker. A worker runs JavaScript on a separate thread, with its own call stack, completely away from the main one. So you send it the data, it does the heavy lifting, and sends back the result as a message. Meanwhile, your main thread stays free, so clicks and timers keep working. Now workers can't touch the page directly, but for pure number crunching, they're perfect.

Part 3What about zero?

Now, what if we set the delay to zero? Does the callback run instantly? So let's see.

zero.js
1console.log("Start");2setTimeout(function cb() {3  console.log("Callback");4}, 0);5console.log("End");
Output
Start
End
Callback

Line one logs Start. Line two registers cb, with a zero millisecond timer. The timer finishes instantly, and cb goes into the callback queue. But the call stack isn't empty. Global is still running. So line five prints End first. Only after the global code is done, does the event loop push cb. And then Callback prints. So Start, End, Callback. Even zero has to wait in line. It's exactly what we saw in episode eleven's quiz, remember? The three threes came after done.

REMEMBER THIS
setTimeout(fn,0)meansafterthe
currentcode,notnow.
useful to defer less important work

So why would anyone write setTimeout with zero? To defer work. If something is less important, like sending analytics, or updating a small counter, you can push it to the end of the line, so the important code, like showing the page, finishes first. So setTimeout with zero means, run this after everything that's running now. Not instantly.

chunks.js
1function processAll(items, start) {2  const end = Math.min(start + 1000, items.length);3  for (let i = start; i < end; i++) {4    handle(items[i]);5  }6  if (end < items.length) {7    setTimeout(function () {8      processAll(items, end);9    }, 0);10  }11}

And now here's a smart way to use it. Say you have a hundred thousand items to process. If you loop through all of them at once, you block the main thread, and the page freezes. So instead, process a thousand items, then schedule the next thousand with setTimeout zero. Between every chunk, the call stack becomes empty for a moment, so the event loop can handle a click, or a timer, or repaint the screen. The work still gets done, but the page stays smooth. So small chunks, with breathing room in between.

BONUS
Browsersclamptimers:
nestedonestoabout4
ms,backgroundtabsto
about1s.
two more reasons it's never exact
TRY IT YOURSELF
VSCode,Chrome,Live
Server:thenDevTools
forthecallstackand
breakpoints.
run every example from this course yourself
INTERVIEW ANSWER
Thedelayisaminimum:
thecallbackrunswhen
thetimerisdoneandthe
stackisempty.
a blocked main thread makes it late

And here are two more reasons setTimeout is never exact. First, browsers set a minimum for deeply nested timers. When a timer schedules another timer, again and again, after a few levels the delay is raised to about four milliseconds. Now second, when a tab is in the background, browsers slow its timers down, often to once a second, to save battery. So timing in JavaScript always means, at least this long.

And now try all of this yourself. You don't need much. Install VS Code, make a folder with an index.html, and a script file. Add the extension called Live Server, and with one click, your page opens in Chrome. Then open DevTools. In the Sources tab, you can put breakpoints, pause your code, and watch the call stack and the scope, live. So run every example from this course that way. Reading is good, but running it yourself is how it really sticks.

Quick quiz
quiz.js
1setTimeout(function () {2  console.log("A");3}, 0);4 5for (let i = 0; i < 3; i++) {6  console.log(i);7}8 9setTimeout(function () {10  console.log("B");11}, 0);12console.log("C");

What's the full order?

Show the answer

So the two timers go to the queue in order, A first, then B. But they can't run until the stack is empty. So first, all the plain code. The loop prints zero, one, two. Then C. Now the stack is empty, and the event loop pushes A, and then B. So zero, one, two, C, A, B. Did you get it?

Your turn

Have you ever had a timer run late, and didn't know why?

Answer in the comments under the video.

Your progress stays on this device.
A new lesson every day at 11 am

The video on YouTube, and the lesson as a swipe-through on Instagram.