Demystifying Async JavaScript – Part 2: setTimeout and setInterval

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);        

  • Schedules callback to run after at least delay milliseconds.
  • The actual execution may be delayed further depending on the event loop.

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);        

  • Runs callback repeatedly, aiming for once every interval ms.
  • If one execution takes longer than the interval, the next may be delayed or skipped.

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

  • clearTimeout(timeoutId) — cancels a setTimeout
  • clearInterval(intervalId) — cancels a setInterval


⚠️ Common Pitfalls

  • setTimeout(..., 0) doesn’t mean "run instantly". It still waits for the stack to clear.
  • Timers are not accurate for precise timing (use requestAnimationFrame for animations).
  • Timer drift can happen due to event loop congestion.


💡 When to Use

  • setTimeout: Delay execution (e.g., debounce, wait-and-retry).
  • setInterval: Polling, simple repeat tasks (though Promises + recursion is safer in many cases).


🧠 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

To view or add a comment, sign in

Others also viewed

Explore topics