π setTimeout vs setInterval β JavaScript Timing Explained


βοΈ Written by Chaitanya Chopde
π¨ Inspired by Devsync β
π§ Why Learn About Timing Functions?
JavaScript is single-threaded β but with functions like setTimeout
and setInterval
, you can schedule tasks in the future.
These are essential for:
Animations
Countdown timers
Polling APIs
Delayed events (e.g. showing a popup after 5 seconds)
π setTimeout
β Run Once After a Delay
jsCopyEditsetTimeout(() => {
console.log("Runs after 2 seconds");
}, 2000);
β Executes only once after the given delay (in milliseconds)
β Real Use Case
jsCopyEditfunction showWelcome() {
console.log("Welcome, Hasnide!");
}
setTimeout(showWelcome, 3000); // Show message after 3 seconds
π setInterval
β Run Repeatedly
jsCopyEditsetInterval(() => {
console.log("Runs every 2 seconds");
}, 2000);
β Executes again and again at every interval
π§ͺ Use Case: Countdown Timer
jsCopyEditlet count = 5;
const interval = setInterval(() => {
console.log(count);
count--;
if (count === 0) {
clearInterval(interval);
console.log("Time's up!");
}
}, 1000);
π§ How They Work Under the Hood
Timers go through the browserβs Web APIs (not JS engine itself)
After delay, they are queued in the event loop
If your main thread is busy, the execution might be delayed
π§Ή Cancelling Timers
clearTimeout(id)
stops asetTimeout
clearInterval(id)
stops asetInterval
jsCopyEditconst timeoutId = setTimeout(() => {}, 1000);
clearTimeout(timeoutId);
const intervalId = setInterval(() => {}, 1000);
clearInterval(intervalId);
β οΈ Common Mistakes
Forgetting to use
clearInterval()
β can cause memory leaksAssuming
setTimeout()
is exact β it's not guaranteed, just minimum delayUsing
setInterval()
wheresetTimeout()
inside recursion would be better for dynamic timing
β Conclusion
Both setTimeout
and setInterval
are simple yet powerful tools that let you control timing in your JavaScript applications.
Whether it's a delayed animation or repeated API checks β these functions are key to interactive experiences.
For Hasnide and all beginners β mastering timers is a must-have in your JavaScript toolkit!
βοΈ Written by:
Chaitanya Chopde
π« chaitanyachopde14@gmail.com
π¨ Blog Inspired by Devsync β Making JavaScript Practical
Subscribe to my newsletter
Read articles from Chaitanya Chopde directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Chaitanya Chopde
Chaitanya Chopde
Hey, I'm Chaitanya Chopde π» Web Development Learner | Frontend Focused π οΈ Learning HTML, CSS, JavaScript & Figma βοΈ Writing to share my dev journey, tips & projects π·οΈ #DevsyncLearning | Building one line of code at a time