Mastering setInterval() in JavaScript

Zia Ur RehmanZia Ur Rehman
3 min read

Title Slide

Mastering setInterval() in JavaScript

Interactive guide to timing, control, and clean coding practices.


Slide 1: What is setInterval()?

  • A built-in JavaScript function

  • Repeatedly executes a callback function at specified intervals (in milliseconds)

  • Syntax: setInterval(callback, delay, ...args)

Visual: Alarm clock ringing every X seconds

Example:

setInterval(() => {
  console.log("Tick");
}, 1000); // Prints "Tick" every second

Slide 2: How Does setInterval() Work Under the Hood?

  • Added to the Web API task queue

  • Callback executes after the delay — not guaranteed to be precise

  • Depends on JS event loop & current call stack

Visual:
Event loop diagram with setInterval being queued

Speaker Note: Great for non-blocking repeated tasks but NOT for time-sensitive precision.


Slide 3: Real-World Use Case #1: Live Clock

setInterval(() => {
  const now = new Date();
  document.getElementById("clock").innerText = now.toLocaleTimeString();
}, 1000);

Visual: Live clock UI


Slide 4: Real-World Use Case #2: Polling an API

setInterval(async () => {
  const response = await fetch("/api/status");
  const data = await response.json();
  updateStatus(data);
}, 5000);

Tip: Add retry logic and error handling!


Slide 5: Real-World Use Case #3: UI Animation (Basic)

let pos = 0;
const box = document.getElementById("box");
const interval = setInterval(() => {
  if (pos >= 300) clearInterval(interval);
  else box.style.left = `${pos++}px`;
}, 10);

Visual: Moving box demo


Slide 6: Common Issue #1 - Memory Leaks

  • Forgetting to clearInterval()

  • Interval keeps running even after it's no longer needed

Example:

useEffect(() => {
  const interval = setInterval(doSomething, 1000);
  return () => clearInterval(interval);
}, []);

Tip: Always clear intervals on unmount in frameworks like React


Slide 7: Common Issue #2 - Overlapping Intervals

  • If callback takes longer than delay

  • Can cause stacking and crashes

Bad:

setInterval(async () => {
  await fetchHeavyData();
}, 1000);

Fix: Use recursive setTimeout

async function poll() {
  await fetchHeavyData();
  setTimeout(poll, 1000);
}
poll();

Slide 8: Common Issue #3 - Incorrect Clearing

  • Forgetting to track interval ID
const id = setInterval(...);
clearInterval(id); // Correct
  • Avoid using clearInterval() without the right ID

Tip: Store IDs in variables or refs


Slide 9: Common Issue #4 - Browser Throttling

  • Inactive tabs slow down intervals

  • setInterval becomes unreliable in background

Best Practice: Use requestAnimationFrame() for animations, setTimeout for better control


Slide 10: Best Practices Recap

  • Always store and clear interval IDs

  • Use setTimeout recursively for async control

  • Avoid for precise timing (e.g., games, metronomes)

  • Prefer requestAnimationFrame() for animations

  • Clean up in componentWillUnmount / useEffect


Slide 11: Visual Analogy - The Kitchen Timer
setInterval: Set a repeating timer, even if the chef is still cooking
setTimeout (recursive): Set a new timer only after cooking ends

Visual: Cartoon of chef and timers


Slide 12: Quick Quiz (Audience Participation!)

  1. What happens if you don’t clear an interval?

  2. Why use recursive setTimeout over setInterval?

  3. When should you avoid using setInterval()?

Visual: Polling buttons (if interactive)


Slide 13: Summary Slide

  • setInterval() is powerful but easy to misuse

  • Understand the event loop and potential side effects

  • Always clean up intervals

  • Prefer setTimeout for async and precise control

  • Use visuals and IDs to track timers


Slide 14: Cheat Sheet 📚 (Screenshot This!)

// Start
const id = setInterval(fn, ms);

// Stop
clearInterval(id);

// Safe async polling
async function loop() {
  await fetchSomething();
  setTimeout(loop, 1000);
}
loop();

// React cleanup
useEffect(() => {
  const id = setInterval(fn, 1000);
  return () => clearInterval(id);
}, []);

Slide 15: Closing Tips ✨

  • Practice with small projects (live clock, API checkers)

  • Don’t fear timers—embrace the control they offer

  • Keep code clean, timed, and well-documented

  • Screenshot the cheat sheet!

  • Questions? Let’s talk!

Thank you! 👋

0
Subscribe to my newsletter

Read articles from Zia Ur Rehman directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Zia Ur Rehman
Zia Ur Rehman

🧐 Are you facing challenges like slow website performance, poor user experience, cross-browser issues, and difficulty integrating with back-end systems, all while trying to manage business growth without a streamlined digital solution? 🤔 Are you struggling to reach a wider audience, improve customer engagement, and stay competitive without a web app, while dealing with inefficient operations, limited scalability, and missed revenue opportunities? 🚀 Build a web app to expand reach, improve engagement, and streamline operations for growth. ⚙️ Optimize performance, enhance user experience, and integrate systems with a smooth, scalable solution. 👨‍💻 I am Zia-Ur-Rehman a MERN Developer with experience in building scalable and high-performing web applications that solve buisness Problems. I worked with the startup to Help their clients by developing highly scalable webApps to make their global buisness mangable with one click across globe. ✅ Frontend Development to create responsive, user-friendly interfaces that solve the problems of your audience. ✅ Figma to Next.js Functional App transforming your designs into interactive, high-performance Web apps. ✅ Web App Development to expand your reach and improve customer engagement.✅ Performance Optimization for faster load times and seamless user experience.✅ Cross-Browser Compatibility ensuring your app works perfectly everywhere.✅ Backend Integration to streamline operations and boost business efficiency.If you have an idea that will capture market share, why are you waiting? 🚀 DM me today or email me (emailtozia0@gmail.com) and get started!