xxxxxxxxxx
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));
xxxxxxxxxx
function debounce(fn, delay) {
let timer;
return (() => {
clearTimeout(timer);
timer = setTimeout(() => fn(), delay);
})();
};
// usage
function logName(name: string) {
return debounce(() => {
console.log(name);
}, 4000);
}
logName('Hi');
xxxxxxxxxx
// 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))
xxxxxxxxxx
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);
xxxxxxxxxx
let timeout = null;
document.addEventListener("wheel", debounce);
function debounce() {
clearTimeout(timeout);
timeout = setTimeout(()=> {
console.log("scroll")
}, 1000)
}
xxxxxxxxxx
function debounce(func, delay) {
let timeoutId;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
func.apply(context, args);
}, delay);
};
}
// Usage example
function search() {
// Perform search functionality
console.log('Searching...');
}
const searchDebounced = debounce(search, 500);
// Call debounced search function
searchDebounced(); // This will wait for 500ms before calling the actual search function