❯ehsan.blog
~/blog/your-30-day-settimeout-fires-in-one-millisecond — zsh
❯cat your-30-day-settimeout-fires-in-one-millisecond.md

Your 30-day setTimeout fires in one millisecond

·10 min read

Your 30-day setTimeout fires in one millisecond — article card for a post by Ehsan Shahid

You want to end a free trial in 30 days, so you reach for setTimeout and write the obvious thing — and it fires one millisecond later:

ts
const THIRTY_DAYS = 30 * 24 * 60 * 60 * 1000

setTimeout(() => {
  endTrial(user.id)
}, THIRTY_DAYS)

The trial ends. Not in 30 days — now, about one millisecond after that line runs. Every user who signs up loses their trial instantly, and the code looks completely correct while it happens.

There is no error. There is no failed promise. In a browser there is not even a message in the console. The number you passed was simply too big, and JavaScript quietly replaced it with 1.

The short version

Timer delays are stored as a 32-bit signed integer. The largest value that fits is 2,147,483,647 milliseconds:

ts
2147483647 / 1000 / 60 / 60 / 24   // 24.855 days

So you get a ceiling of just under 24 days and 21 hours. Pass anything larger and the delay is not clamped to the maximum, which is what most people assume. In Node it is set to 1.

That difference matters enormously. A clamped timer would fire 24 days late — annoying, but you would probably notice during testing. A timer reset to 1 fires immediately, which looks like your callback was never scheduled at all.

Node’s docs state the rule outright: “When delay is larger than 2147483647 or less than 1 or NaN, the delay will be set to 1” — see the Node timers documentation. Browsers reach the same ceiling by a different and nastier route, which I get to further down.

Watching it happen

I registered a batch of timers with different delays and recorded which ones fired within 300 milliseconds. Node v22.16.0:

text
MAX-1 (2147483646)   did not fire
MAX   (2147483647)   did not fire
MAX+1 (2147483648)   FIRED at 4ms
25 days              FIRED at 4ms
30 days              FIRED at 4ms
1 year               FIRED at 4ms
Infinity             FIRED at 4ms
NaN                  FIRED at 4ms
-5000                FIRED at 4ms
undefined            FIRED at 4ms

The boundary is exact. At 2,147,483,647 the timer behaves properly. One millisecond more and it fires straight away.

Node does tell you, on stderr:

text
(node:25336) TimeoutOverflowWarning: 2592000000 does not fit into a 32-bit
signed integer. Timeout duration was set to 1.

That last sentence is the whole bug, stated plainly. The problem is where it appears: on stderr, as a process warning, mixed in with everything else your app writes at startup. If your logger does not capture stderr, or you only read structured logs, you will never see it.

You can also read the stored value straight off the timer object in Node:

ts
const h = setTimeout(() => {}, 30 * 86400 * 1000)
console.log(h._idleTimeout)   // 1
flowchart TD
  A["setTimeout(fn, delay)"] --> B{"delay fits in a<br/>32-bit signed int?"}
  B -->|"1 to 2147483647"| C["waits the real delay"]
  B -->|"NaN, undefined, negative"| E["delay becomes 1<br/>no warning anywhere"]
  B -->|"above 2147483647"| D{"which runtime?"}
  D -->|"Node"| F["delay becomes 1<br/>TimeoutOverflowWarning on stderr"]
  D -->|"Chrome"| G["delay wraps modulo 2^32<br/>silence"]
  E --> H["runs almost immediately"]
  F --> H
  G --> I["runs at some other<br/>unrelated time"]

setInterval is the one that will page you

setTimeout firing early is a correctness bug. setInterval firing early is an outage.

A monthly cleanup job looks harmless:

ts
setInterval(runMonthlyCleanup, 30 * 24 * 60 * 60 * 1000)

The period becomes 1, so it does not run monthly. It runs roughly a thousand times a second, forever. I counted the ticks over a 250 millisecond window:

text
setInterval(30 days) ticks in 250ms: 209

That is 836 calls per second to a function you expected to run twelve times a year. If it touches the database, you have just written a denial-of-service attack against your own backend, scheduled by a line of code that reads like a cron entry.

The promise-based timers have the same ceiling, which is easy to miss because await makes the code look so calm:

ts
import { setTimeout as sleep } from 'node:timers/promises'

await sleep(30 * 86400 * 1000)   // resolves after ~2ms
console.log('a month has passed')

I measured that resolving in 2 milliseconds.

The values that break without any warning

Look again at the measurement table. NaN, undefined and -5000 all fired immediately too — but those three produce no warning at all, in Node or anywhere else.

This is a different rule with an identical symptom. Any delay below 1, including a negative number, and any value that is not a number, is treated as 1. That behaviour is intentional and documented. It only becomes confusing because the overflow bug looks exactly the same from the outside.

So “my callback ran immediately” has two possible causes, and in Node only one of them warns:

What you passedResult in NodeWarning in Node?
2147483648 or largerruns at onceyes, TimeoutOverflowWarning
Infinityruns at onceyes
NaNruns at onceno
undefinedruns at onceno
a negative numberruns at onceno

Infinity warning while NaN stays silent is worth remembering, because Infinity is what you get from dividing by zero and NaN is what you get from arithmetic on undefined — and those two mistakes usually live in the same function.

Where a 30-day delay comes from when nobody typed one

Almost nobody writes 30 * 86400 * 1000 and gets surprised. The real bugs come from arithmetic on a timestamp, and the classic one is a JWT.

The exp claim in a JWT is seconds since the epoch, not milliseconds. So you multiply by 1000 to get milliseconds, and then it is very easy to forget the second half of the sum:

ts
// token expires in one hour
const exp = 1792146726          // seconds since epoch

const wrong = exp * 1000                // 1792146726000
const right = exp * 1000 - Date.now()   //       3599366

Those are both “milliseconds”, both positive, and both perfectly reasonable looking in a debugger. The first one is 20,742 days, so:

ts
setTimeout(refreshToken, exp * 1000)   // fires in 1ms

Your refresh handler runs immediately, gets a fresh token, schedules the next refresh the same broken way, and runs immediately again. That is an infinite token-refresh loop against your auth server, caused by a missing - Date.now(). I wrote about the other half of this problem, the race when several requests all refresh at once, in auth, all four ways, and the OAuth2 refresh race.

The same shape shows up anywhere you subtract dates: expiresAt - Date.now() where expiresAt was already a duration, a date parsed from a column that turned out to be seconds, or a “never expires” sentinel stored as a year 9999 timestamp.

The fix

You cannot raise the 32-bit ceiling, so you wait in stages. Sleep for at most the maximum, then check how much time is actually left and sleep again:

ts
const MAX_DELAY = 2147483647   // 2 ** 31 - 1

export function setLongTimeout(fn: () => void, delay: number) {
  const deadline = Date.now() + delay
  let handle: ReturnType<typeof setTimeout>

  const arm = () => {
    const left = deadline - Date.now()
    if (left <= MAX_DELAY) {
      handle = setTimeout(fn, Math.max(0, left))
    } else {
      handle = setTimeout(arm, MAX_DELAY)
    }
  }

  arm()
  return { clear: () => clearTimeout(handle) }
}

Two details in there are doing real work.

It recomputes left from a deadline instead of subtracting a fixed chunk. A timer never fires at exactly the millisecond you asked for, so if you subtracted MAX_DELAY each round the small overshoots would add up. Measuring against deadline every time means each stage absorbs the previous stage’s drift.

It returns an object with a clear method, not a timer id. The id changes on every stage, so the caller cannot hold on to it. Returning a closure over the current handle is the smallest thing that keeps the timer cancellable.

Proof it works

Waiting 30 days to test a 30-day timer is not practical, so I made the limit a parameter and shrank it. With a pretend ceiling of 50 milliseconds, a 320 millisecond delay has to span about seven stages — the same code path a real 60-day timer takes, just compressed:

text
TEST 1 long timer: fired at 320ms (target 320ms) — drift 0ms
TEST 2 cancelled timer stayed silent: YES
TEST 3 short timer fired at 61ms (target 60ms)
TEST 4 30-day timer fired early? NO
TEST 4 emitted TimeoutOverflowWarning? NO

Zero drift across seven stages, cancellation works mid-chain, delays under the limit are untouched, and a real 30-day delay now neither fires early nor warns.

One honest caveat: because this chases a wall-clock deadline, it follows the system clock. If the clock jumps forward an hour, the timer fires an hour early. For “end this trial at this moment” that is exactly what you want. If you need a true elapsed-time measurement that ignores clock changes, you have to track the remaining duration yourself and accept the drift instead.

In the browser, the number wraps instead

Here is the part I got wrong until I measured it, and the reason this bug is worse than “it fires immediately”.

Node clamps: anything over the limit becomes 1, full stop. Chrome wraps, like a car odometer rolling past its last digit. The same delays in Chrome 152:

text
2**32 + 5000  ->  fired at 5001ms
2**32 + 2000  ->  fired at 2001ms
2**32 - 5000  ->  fired at 0ms
2**31 + 1000  ->  fired at 1ms
30 days       ->  fired at 1ms

Read the first line again. A delay of 2**32 + 5000 milliseconds is about 49.7 days. In Chrome it fired after five seconds — because 2³² wraps around to zero and leaves the 5000 behind. The same values in Node all fired at once instead:

delay≈ real durationNodeChrome
2**32 + 500049.7 days1 ms5 s
2**32 + 200049.7 days1 ms2 s
2**32 - 500049.7 days1 ms0 ms
30 * 86400 * 100030 days1 ms1 ms

MDN documents the wrapping, including the detail that 2 ** 32 - 5000 overflows to a negative number and so runs immediately, in Maximum delay value.

This is why “it fires immediately” is an incomplete description of the bug. In a browser an over-limit delay does not fire immediately — it fires at a time with no relationship to anything, and the number you get out depends on where your delay happens to land after wrapping. A 30-day timer firing instantly at least looks broken. A 49.7-day timer firing after five seconds looks like a different bug entirely, somewhere else in your code.

Chrome’s console stayed completely empty through all of it. No warning, no deprecation notice, nothing.

The setInterval version is slightly less violent in the browser, because Chrome clamps nested timers to 4 milliseconds: I counted 55 ticks in 200 milliseconds instead of Node’s 209. That is still 275 calls per second from a line that says “once a month”, and it will keep a laptop fan running.

The rule worth keeping

Any timer delay you did not type as a literal deserves a bounds check, because the failure mode is not “late”, it is “right now”.

Three things to carry away:

  1. The ceiling is 2,147,483,647 ms, about 24.9 days. Above it, Node sets the delay to 1 and Chrome wraps it modulo 2³² — so the callback runs either immediately or at some unrelated time, depending on the runtime.
  2. NaN, undefined and negative delays also become 1, and those produce no warning anywhere.
  3. If a delay comes out of date arithmetic, log it once before you schedule it. A single console.log(delay) would have caught every example in this post.

If you want the cheapest possible guard, make the bad case loud instead of silent:

ts
if (!Number.isFinite(delay) || delay < 0 || delay > MAX_DELAY) {
  throw new RangeError(`refusing to schedule a timer with delay ${delay}`)
}

Throwing beats a trial that ends on signup. For the related trap where a timeout you did set correctly still expires too early, see your fetch timeout starts before the request does.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.