webdev-power-kit
Version:
A powerful toolkit that simplifies access to browser features like clipboard, notifications, battery, vibration, and more — perfect for modern web developers.
47 lines (46 loc) • 1.6 kB
JavaScript
/**
* @fileoverview Throttle utility — limits how often a function can run.
* Useful for scroll events, mouse moves, resize, etc.
*/
/**
* Creates a throttled version of the given function.
* @param fn - Function to throttle
* @param interval - Minimum time (in ms) between calls
* @returns A throttled function
*/
export function throttle(fn, interval) {
if (typeof fn !== 'function') {
throw new TypeError('[webdev-power-kit][throttle] First argument must be a function.');
}
if (typeof interval !== 'number' || interval < 0) {
throw new TypeError('[webdev-power-kit][throttle] Interval must be a non-negative number.');
}
let lastCalled = 0;
let timeoutId = null;
return function throttledFn(...args) {
const now = Date.now();
const timeSinceLastCall = now - lastCalled;
if (timeSinceLastCall >= interval) {
lastCalled = now;
try {
fn(...args);
}
catch (err) {
console.error('[webdev-power-kit][throttle] Function threw an error:', err);
}
}
else if (!timeoutId) {
const timeRemaining = interval - timeSinceLastCall;
timeoutId = setTimeout(() => {
timeoutId = null;
lastCalled = Date.now();
try {
fn(...args);
}
catch (err) {
console.error('[webdev-power-kit][throttle] Function threw an error:', err);
}
}, timeRemaining);
}
};
}