How to use setTimeout and setInterval in JavaScript
· Category: JavaScript
Short answer
setTimeout runs a function once after a delay, while setInterval repeats it at fixed intervals. Both return an identifier you can pass to clearTimeout or clearInterval to cancel.
Steps
- Delay execution:
javascript const timer = setTimeout(() => { console.log("Fired after 1 second"); }, 1000); - Repeat execution:
javascript const interval = setInterval(() => { console.log("Every 2 seconds"); }, 2000); - Cancel timers:
javascript clearTimeout(timer); clearInterval(interval); - Use recursive
setTimeoutfor variable intervals:javascript function tick() { console.log("tick"); setTimeout(tick, Math.random() * 1000); }
Tips
- Timer delays are not guaranteed; they are minimum delays due to the event loop.
- Prefer
setTimeoutrecursion oversetIntervalwhen task duration may exceed the interval.
Common issues
- Forgetting to clear intervals causes memory leaks and unwanted background work.
thisinside timer callbacks defaults to the global object unless bound or using an arrow function.