How to Fix setInterval Not Working in JavaScript
In this tutorial, you'll learn about How to Fix setInterval Not Working in JavaScript. We cover key concepts, practical examples, and best practices.
The Problem
setInterval() either does not run the callback, runs it only once, or continues running when it should stop, typically due to incorrect delay values, scope issues, or the callback throwing an error.
Quick Fix
Step 1: Ensure the delay is a positive number
A delay of 0 or negative value causes issues:
const id = setInterval(() => {
console.log('Running');
}, 0);
This runs as fast as possible, blocking the main thread. Use a minimum of 4ms (browser-enforced minimum):
const id = setInterval(() => {
console.log('Running');
}, 100);
Step 2: Store the interval ID and clear it properly
Not storing the ID prevents stopping the interval:
setInterval(() => {
console.log('Still running');
}, 1000);
Store the ID:
const intervalId = setInterval(() => {
console.log('Running');
}, 1000);
setTimeout(() => {
clearInterval(intervalId);
console.log('Stopped');
}, 5000);
Step 3: Handle errors inside the callback
An uncaught error in the callback stops the interval:
setInterval(() => {
throw new Error('Something went wrong');
}, 1000);
Error: Something went wrong
The interval stops after the first error. Wrap in try/catch:
setInterval(() => {
try {
updateData();
} catch (error) {
console.error('Interval failed:', error.message);
}
}, 1000);
Step 4: Use recursive setTimeout for dynamic intervals
If the interval delay needs to change after each execution, use recursive setTimeout:
function poll(delay = 1000) {
setTimeout(() => {
fetchData().then(() => {
poll(adjustDelay());
});
}, delay);
}
poll();
Step 5: Check for inactive tabs (browsers throttle intervals)
Browsers throttle intervals to 1 second when the tab is inactive:
// This runs at most once per second when tab is hidden
setInterval(() => {
updateAnimation();
}, 100);
Use requestAnimationFrame for animations or Web Workers for background tasks.
Prevention
- Always store the interval ID returned by
setInterval. - Use
clearInterval()in cleanup functions (component unmount, page unload). - Wrap interval callbacks in try/catch.
- Use recursive
setTimeoutfor variable delays. - Be aware that browsers throttle intervals in inactive tabs.
Common Mistakes with setinterval not working
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro