Course contentsShow
← JavaScript
Lesson 2388 of 2,72349. Common Patterns and IdiomsFree lesson

Implementing a Simple Throttle

Write a basic throttle function using a timestamp gate to limit execution frequency.

Implementing a Simple Throttle

You'll learn how to build a basic throttle function that uses a timestamp to ensure a callback executes no more than once per time interval.

The Core Idea

While debounce delays execution until activity stops, throttle limits execution frequency during continuous activity. A throttled function will execute immediately the first time, then ignore subsequent calls until a specified time period has passed.

The timestamp gate pattern works by recording the last execution time. Each new call checks if enough time has elapsed since that timestamp. If yes, execute and update the timestamp. If no, ignore the call.

Basic Implementation

function throttle(func, limit) {
  let lastRan = 0; // Timestamp of last execution
  
  return function(...args) {
    const now = Date.now();
    
    if (now - lastRan >= limit) {
      func.apply(this, args);
      lastRan = now; // Update the gate timestamp
    }
    // Otherwise, silently ignore the call
  };
}

// Usage: limit scroll handler to once per 200ms
const handleScroll = throttle(() => {
  console.log('Scroll position:', window.scrollY);
}, 200);

window.addEventListener('scroll', handleScroll);

How the Timestamp Gate Works

  1. lastRan starts at 0, so the first call always passes the check
  2. On execution, lastRan updates to the current timestamp
  3. Subsequent calls within the limit period fail the time check
  4. Once limit milliseconds pass, the gate opens again

Think of it like a security checkpoint that only lets one person through every 200 milliseconds—early arrivals are turned away.

Key Takeaway: A simple throttle uses a timestamp variable to create a time gate, ensuring a function executes at most once per specified interval, perfect for rate-limiting high-frequency events like scrolling or resizing.