snippetjavascriptModeratepending
Throttle function — vanilla JavaScript implementation
Viewed 0 times
throttlescroll handlerresizerate limitrequestAnimationFrame
browsernodejs
Problem
Need to limit how often a function runs — at most once per interval. Unlike debounce, throttle guarantees execution at regular intervals during continuous invocation. Useful for scroll, resize, and mousemove handlers.
Solution
Throttle implementation that fires on the leading edge and optionally on the trailing edge.
Code Snippets
Throttle with trailing call
function throttle(fn, ms) {
let lastCall = 0;
let timer;
return (...args) => {
const now = Date.now();
const remaining = ms - (now - lastCall);
clearTimeout(timer);
if (remaining <= 0) {
lastCall = now;
fn(...args);
} else {
timer = setTimeout(() => {
lastCall = Date.now();
fn(...args);
}, remaining);
}
};
}
// Usage
window.addEventListener('scroll',
throttle(() => console.log(window.scrollY), 100)
);Revisions (0)
No revisions yet.