JavaScript

Throttle

admin by @admin ADMIN
1d ago
Apr 28, 2026
Public
0 0 up · 0 down Sign in to vote
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
Raw
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.