JavaScript
Throttle Function
Limit a function to execute at most once within a time interval.
By EZ4Code Team
functionperformancethrottle
Code
function throttle(fn, interval = 300) {
let lastTime = 0;
let timer = null;
return function (...args) {
const now = Date.now();
const remaining = interval - (now - lastTime);
if (remaining <= 0) {
if (timer) { clearTimeout(timer); timer = null; }
lastTime = now;
fn.apply(this, args);
} else if (!timer) {
timer = setTimeout(() => {
lastTime = Date.now();
timer = null;
fn.apply(this, args);
}, remaining);
}
};
}Explanation
Throttle ensures a function executes at most once per fixed interval, suitable for scrolling, dragging, etc.
More JavaScript Snippets
Array Map Filter Reduce
Chain map, filter, reduce, find, some, and every on arrays.
Array Deduplication
Deduplicate an array using Set.
Deep Clone
Deep clone objects, supporting common data types.
Debounce Function
Wait a period of time after an event triggers before executing; reset the timer if triggered again during the wait.
Promise.all Concurrency Control
A Promise executor with concurrency limit.
async/await Error Handling
Wrap async functions to uniformly catch exceptions.