JavaScript

Throttle

by @admin
10h ago
Apr 28, 2026
Public
Ensures a function is called at most once per specified time interval, no matter how many times the trigger fires. Ideal for scroll listeners, mousemove handlers, and window resize events where you need regular updates but not every single frame.
JavaScript
function throttle(fn, limit = 300) {
  let lastRun = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastRun >= limit) {
      lastRun = now;
      return fn.apply(this, args);
    }
  };
}

// Usage
const onScroll = throttle(() => {
  console.log('scroll Y:', window.scrollY);
}, 200);

window.addEventListener('scroll', onScroll);
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.