@widergy/web-utils
Version:
Utility GO! Web utils
59 lines (58 loc) • 1.75 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.throttle = exports.debounce = exports.polling = void 0;
const polling = (func, interval = 300, timeout, timeoutCallback) => {
const intervalId = setInterval(func, interval);
if (timeout)
setTimeout(() => {
clearInterval(intervalId);
if (timeoutCallback)
timeoutCallback();
}, timeout);
return intervalId;
};
exports.polling = polling;
const debounce = (func, wait = 100, immediate) => {
let timeout;
return function debounced(...args) {
const context = this;
const later = () => {
timeout = null;
if (!immediate)
func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow)
func.apply(context, args);
};
};
exports.debounce = debounce;
const throttle = (func, limit = 100) => {
let lastFunc;
let lastRan;
return function throttled(...args) {
const context = this;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
}
else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
if (Date.now() - lastRan >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
};
exports.throttle = throttle;
const FUNCTION_UTILS = {
polling: exports.polling,
debounce: exports.debounce,
throttle: exports.throttle
};
exports.default = FUNCTION_UTILS;