setTimeout in a React component fires at the wrong time or never
The callback runs immediately instead of after the delayShort answer
setTimeout needs a function to call later. Most React cases are one of four things: you called the function instead of passing it, the callback reads old state, an effect never cleared its timer, or the browser delays timers in a background tab. Find which one by logging inside the callback.
Fix it fast
1Find out which cause you have
Log a timestamp when you schedule the timer and another one inside the callback. The gap shows whether the delay is skipped, correct or stretched.
console.log('scheduled', Date.now()); setTimeout(() => console.log('ran', Date.now()), 2000);2Match what you see, then jump to its fix
- 1
The code runs the moment the component renders, not after the delayThe function is called, not passedFix - 2
The callback runs twice in development, or after you left the screenThe timer keeps firing after the component changes or unmountsFix - 3
The timer sets or shows a value that is one step behindThe callback reads a state value from an earlier renderFix - 4
The timer is correct in the foreground tab but late when the tab is hiddenThe browser delays timersFix - 5
TypeError: Cannot read properties of undefinedA class method loses this inside the timerFix
- 1
What does the error look like?
The callback runs immediately instead of after the delayThe timer uses an old state valueThe timer fires twice in developmentA timer in a background tab runs much later than the delay
Cause 1 of 5
The function is called, not passed
1Check
Look at the first argument of setTimeout. A name followed by parentheses runs the function now and hands its return value to the timer. MDN's examples pass the function itself.
grep -rn "setTimeout(" src/2Fix
Pass the function, or wrap the call in an arrow function when you need arguments.
// wrong: runs now
setTimeout(hideBanner(id), 3000);
// right
setTimeout(() => hideBanner(id), 3000);3Verify
The log shows the 'ran' time about three seconds after 'scheduled'.
console.log(Date.now())Confirmed by developer.mozilla.org
Cause 2 of 5
The timer keeps firing after the component changes or unmounts
1Check
Strict Mode in development runs one extra setup and cleanup cycle for effects, so an effect that starts a timer without cleaning it up starts it twice.
grep -rn "setTimeout" src/ | grep -v clearTimeout2Fix
Keep the timer id inside the effect and clear it in the cleanup function.
useEffect(() => {
const id = setTimeout(() => setVisible(false), 3000);
return () => clearTimeout(id);
}, []);3Verify
In development the callback now fires once, and nothing happens after you navigate away.
npm run devConfirmed by react.dev
Cause 3 of 5
The callback reads a state value from an earlier render
1Check
A callback captures the values of the render that created it. If the effect lists the value as a dependency, the timer restarts on every change.
grep -rn "setCount(count" src/2Fix
Use an updater function so the callback does not need the value in its closure.
useEffect(() => {
const id = setTimeout(() => setCount(c => c + 1), 1000);
return () => clearTimeout(id);
}, []);3Verify
The counter increases by one each time the timer fires.
console.log('tick')Confirmed by react.dev
Cause 4 of 5
The browser delays timers
1Check
The delay is not exact: it may be longer than set. Browsers enforce a minimum delay in inactive tabs, and Chrome checks throttled timers once per second, or once per minute with intensive throttling.
document.visibilityState2Fix
Do not use timers for exact time. Store a start time and compute the elapsed time when the callback or the tab visibility changes.
const start = Date.now();
setTimeout(() => {
const elapsed = Date.now() - start;
console.log(elapsed);
}, 1000);3Verify
The elapsed value is logged and your UI uses it, not an assumed delay.
console.log(document.visibilityState)Confirmed by developer.mozilla.org
Cause 5 of 5
A class method loses this inside the timer
1Check
A non-arrow function passed to setTimeout runs with normal call semantics, so this is not your component or object.
grep -rn "setTimeout(this\." src/2Fix
Wrap the call in an arrow function or bind the method.
setTimeout(() => this.refresh(), 1000);
// or
setTimeout(this.refresh.bind(this), 1000);3Verify
The method runs without the TypeError after the delay.
console.log('refreshed')Confirmed by developer.mozilla.org
How do I stop it coming back?
- Always keep the id from setTimeout in an effect and clear it in the cleanup.
- Use updater functions for state changes inside timers.
- Do not rely on timers for exact timing; compute elapsed time from Date.now().
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
Related fixes
Web apps
React shows Attempted import error when importing a component or function
Attempted import error:
The build found the file but not the name you asked for.
2 causes, each with a fixWeb apps
AxiosError Network Error with code ERR_NETWORK in a React app
Network Error
ERR_NETWORK means the request produced no readable response.
4 causes, each with a fixWeb apps
Axios get works with a URL string but ignores the object passed as the second argument
The server log shows a GET with no query string
axios.get takes a URL and an optional config object.
3 causes, each with a fixWeb apps
Can't resolve '../axios' in a React project
Module not found: Error: Can't resolve '../axios'
A path that starts with ./ or ../ is a file path, not the axios package.
3 causes, each with a fixWeb apps
Axios returns 401 from a React app but the login works elsewhere
Error: Request failed with status code 401
A 401 means the server received the request without valid credentials.
3 causes, each with a fixWeb apps
An axios call never finishes when the API server stops answering
code: 'ECONNABORTED'
Axios has no timeout unless you give it one: the default is 0, which means wait forever.
3 causes, each with a fix