Create a throttled function that limits the execution rate to at most once per specified time interval.
Code
Boilerplatesconst throttle = (fn, ms) => {
let inThrottle;
return (...args) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => inThrottle = false, ms);
}
};
};
const log = throttle(() => console.log('called'), 100);
log();
return 'throttled';Browser·fetch() may be limited by CORS
More JavaScript Snippets
Debounce
Create a debounced function that delays execution until after a specified wait period has elapsed since the last call.
Memoize
Cache function results to avoid redundant calculations and improve performance for expensive operations.
Once
Create a function that can only be called once, returning the cached result for subsequent invocations.
Parallel with Limit
Run promises in parallel with a concurrency limit to control resource usage and prevent overwhelming external services.
Promise.allSettled
Wait for all promises to settle, whether they resolve or reject.
Promise.any
Return the result of the first promise that resolves successfully.