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
lastRanstarts at0, so the first call always passes the check- On execution,
lastRanupdates to the current timestamp - Subsequent calls within the
limitperiod fail the time check - Once
limitmilliseconds 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.