Mastering JavaScript Timers: setTimeout, setInterval, and Their Pitfalls
Learn how JavaScript’s setTimeout and setInterval functions work, see practical code examples, understand their timing inaccuracies and common pitfalls, and discover how recursive setTimeout can provide more reliable scheduling by avoiding overlapping executions.
setTimeout
The setTimeout() method schedules a function or expression to run after a specified number of milliseconds.
setTimeout(function(){
console.log('hello');
}, 1000);This code logs "hello" to the console after 1 second; the timer runs only once. setTimeout returns an ID that can be passed to clearTimeout() to cancel the pending execution.
var t = setTimeout(function(){
alert('hello');
}, 1000);
clearTimeout(t);setInterval
setInterval()works like setTimeout() but repeats the execution at the given interval.
var t = setInterval(function(){
console.log('hello');
}, 1000);The above code outputs "hello" to the console every second. The interval can be stopped with clearInterval():
clearInterval(t);Timer Issues
Both setTimeout and setInterval are not perfectly precise. For example, a setTimeout scheduled for 10 ms may be delayed if the event loop is busy, and setInterval suffers from two main problems:
Intervals may be skipped.
Intervals may be shorter than the specified time.
Consider the following code where a click handler starts a repeated task:
function click(){
// code block1...
setInterval(function(){
// process ...
}, 200);
// code block2
}If the processing takes longer than the interval, subsequent scheduled executions are delayed or skipped, because the JavaScript engine processes only one pending task at a time.
Using Recursive setTimeout to Avoid Overlap
A common solution is to replace setInterval with a recursive setTimeout, which schedules the next execution only after the current one finishes:
setTimeout(function(){
// processing
setTimeout(arguments.callee, interval);
}, interval);Each call creates a new timer, and the next timer is set after the current processing completes, preventing overlapping executions and ensuring a minimum gap equal to interval between runs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
