function debounce(fn, delay) {
let timer;
return (() => {
clearTimeout(timer);
timer = setTimeout(() => fn(), delay);
})();
};
// usage
function someFn() {
console.log('Hi')
};
debounce(someFn, 1000);
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));
function debounce(func, timeout = 300){
let timer;
return function(...args) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(this, args);
}, timeout);
};
}
// Add this in HTML
<button id="myid">Click Me</button>
// This is JS Code for debounce function
const debounce = (fn,delay ) => {
let timeoutID; // Initially undefined
return function(...args){
// cancel previously unexecuted timeouts
if(timeoutID){
clearTimeout(timeoutID);
}
timeoutID = setTimeout( () => {
fn(...args);
}, delay)
}
}
document.getElementById('myid').addEventListener('click', debounce(e => {
console.log('you clicked me');
}, 2000))
let timeout;
const debounce = (callback, wait) => {
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(function () {
callback.apply(this, args);
}, wait);
};
};
const exampleFn = () => {
console.log('Hello Word')
};
debounce(exampleFn, 1000);