debounce js
function debounce(fn, delay) {
let timer;
return (() => {
clearTimeout(timer);
timer = setTimeout(() => fn(), delay);
})();
};
// usage
function someFn() {
console.log('Hi')
};
debounce(someFn, 1000);
debounce js
const debounce = (fn, delay) => {
let timer;
return function () {
clearTimeout(timer);
timer = setTimeout(fn, delay);
};
};
// Example
let count = 0;
const increaseCount = (num) => {
count += num;
console.log(count);
};
window.addEventListener('scroll', debounce(increaseCount.bind(null, 5), 200));
debounce js
function debounce(func, timeout = 300){
let timer;
return function(...args) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(this, args);
}, timeout);
};
}
|