JavaScript Timing Events

Complete interactive guide to setTimeout(), setInterval(), and timing control

1. Timing Methods Overview

⏰
setTimeout()
setTimeout(function, delay)
Executes a function once after a specified delay (in milliseconds). Returns a timeout ID that can be used to cancel the execution.
πŸ”„
setInterval()
setInterval(function, interval)
Repeatedly executes a function at specified time intervals (in milliseconds). Returns an interval ID that can be used to stop the execution.
⏹️
clearTimeout() & clearInterval()
clearTimeout(id) / clearInterval(id)
Stops the execution of setTimeout() or setInterval() using their returned IDs. Essential for managing and cleaning up timers.
🎬
requestAnimationFrame()
requestAnimationFrame(callback)
Optimized for animations. Runs before the next repaint (usually 60fps). Better performance than setInterval for animations.
Timing Events Output
[Ready] πŸ‘ˆ Click any timing button to see results here

2. Timer Visualization

Active Timers
0

setTimeout()

0s
Ready

setInterval()

0
Ready

Animation

0
Ready

3. Countdown Timer Demo

Countdown Timer
10:00
Ready to start
// Countdown Timer Implementation
class CountdownTimer {
  constructor(seconds) {
    this.totalSeconds = seconds;
    this.remainingSeconds = seconds;
    this.timerId = null;
    this.isRunning = false;
  }

  start() {
    if (this.isRunning) return;
    this.isRunning = true;
    
    this.timerId = setInterval(() => {
      this.remainingSeconds--;
      this.updateDisplay();
      
      if (this.remainingSeconds <= 0) {
        this.stop();
        alert("Time's up!");
      }
    }, 1000);
  }

  pause() {
    this.isRunning = false;
    clearInterval(this.timerId);
  }

  reset() {
    this.pause();
    this.remainingSeconds = this.totalSeconds;
    this.updateDisplay();
  }

  updateDisplay() {
    const minutes = Math.floor(this.remainingSeconds / 60);
    const seconds = this.remainingSeconds % 60;
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  }
}

4. Stopwatch Demo

Stopwatch
00:00.00
Ready
No lap times recorded yet

5. Real-World Examples

// Real-world timing implementations

// 1. Debounce - delays execution until after wait time
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

// 2. Throttle - limits execution to once per period
function throttle(func, limit) {
  let inThrottle;
  return function() {
    const args = arguments;
    const context = this;
    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

// 3. Polling - checks for updates periodically
function startPolling(url, interval, callback) {
  const poll = () => {
    fetch(url)
      .then(response => response.json())
      .then(data => callback(data));
  };
  poll(); // Immediate first call
  return setInterval(poll, interval);
}

6. Scheduled Task Manager

No scheduled tasks. Schedule some tasks above!

7. Timing Methods Comparison

Method Execution Returns Cancellation Use Case Performance
setTimeout() Once after delay Timeout ID clearTimeout(id) Delayed actions, debouncing ⭐️⭐️⭐️⭐️
setInterval() Repeatedly at intervals Interval ID clearInterval(id) Clocks, polls, animations ⭐️⭐️⭐️
requestAnimationFrame() Before next repaint Animation ID cancelAnimationFrame(id) Smooth animations ⭐️⭐️⭐️⭐️⭐️
setImmediate() Next event loop cycle Immediate ID clearImmediate(id) Non-blocking execution ⭐️⭐️⭐️⭐️
Promise.resolve().then() Microtask queue Promise N/A Async operations ⭐️⭐️⭐️⭐️⭐️
// Best Practices for Timing Events

// 1. Always clear timers when done
let timerId = setTimeout(() => {
  console.log("Done");
}, 1000);

// Clean up if component unmounts
// clearTimeout(timerId);

// 2. Avoid memory leaks with intervals
const intervalId = setInterval(() => {
  // Your code
}, 1000);

// Clear when no longer needed
// clearInterval(intervalId);

// 3. Use requestAnimationFrame for animations
function animate() {
  // Animation logic
  animationId = requestAnimationFrame(animate);
}

// Stop animation when done
// cancelAnimationFrame(animationId);

// 4. Be careful with recursive setTimeout
function recursiveTimeout() {
  // Do work
  setTimeout(recursiveTimeout, 1000);
}

// 5. Handle page visibility changes
document.addEventListener('visibilitychange', () => {
  if (document.hidden) {
    // Pause timers
  } else {
    // Resume timers
  }
});