Demystifying Async JavaScript – Part 2: setTimeout and setInterval
🔗 Missed Part 1? Start here: Understanding the JavaScript Event Loop
Timers are often the first async tool JavaScript developers encounter — but they’re also the most misunderstood.
Let’s break down how setTimeout and setInterval really work under the hood.
⌛ setTimeout
setTimeout(callback, delay);
Example:
console.log('Start');
setTimeout(() => {
console.log('Timeout');
}, 0);
console.log('End');
🧾 Output:
Start
End
Timeout
Even with 0ms delay, the callback is queued as a macrotask and only runs when the call stack is clear.
🔁 setInterval
setInterval(callback, interval);
Example:
let count = 0;
const id = setInterval(() => {
console.log(++count);
if (count === 3) clearInterval(id);
}, 1000);
🧾 Output:
1
2
3
Runs every second and stops after 3 times.
🧼 Clearing Timers
⚠️ Common Pitfalls
💡 When to Use
🧠 Up Next:
👉 Part 3: Promises — Your First Step into Async We'll explore what Promises are, how they work, and how they’re different from timers.
🔔 Follow me to keep up with the full series on Async JavaScript.
#JavaScript #AsyncJS #setTimeout #setInterval #EventLoop #radikadilanka #WebDevelopment #FrontendTips #Coding