Throttle a function
Run a function at most once per interval, calling immediately and again at the end of a burst.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
function throttle(fn, interval = 200) {
let last = 0;
let timer;
let pendingArgs;
return function throttled(...args) {
const now = Date.now();
const remaining = interval - (now - last);
pendingArgs = args;
if (remaining <= 0) {
clearTimeout(timer);
timer = undefined;
last = now;
fn.apply(this, args);
} else if (!timer) {
timer = setTimeout(() => {
last = Date.now();
timer = undefined;
fn.apply(this, pendingArgs);
}, remaining);
}
};
}How it works
Throttling guarantees a function runs at most once every interval ms. This version fires immediately (leading edge) and also schedules one trailing call with the latest arguments, so the final state is never lost, which suits scroll and resize handlers.
Prefer requestAnimationFrame for purely visual updates.
Related snippets
- Python Tested
Time a block of code with a context manager
Measure elapsed wall-clock time of a with-block using time.perf_counter.
- PHP Tested
Read a large CSV file with a generator
Stream CSV rows as associative arrays using fgetcsv, without loading the whole file into memory.
- JavaScript Tested
Run async tasks with a concurrency limit
Process a large list with at most N promises in flight at once, preserving result order.
- Bash
Run commands in parallel with xargs
Process many files concurrently with xargs -P, safely handling spaces and newlines in names.

