Simple Debounce Implementation in Javascript

Kunal Singh

Sep 7, 2024

function myDebounce(cb, timeout) {
let timer = null;
return function (...args) { // Capture arguments
const context = this; // Preserve the calling context
if(timer){
clearTimeout(timer);
}
timer = setTimeout(function() {
cb.apply(context, args); // Pass arguments and context to the callback
}, timeout);
}
}

function log(message) {
console.log(message);
}

let debouncedLog = myDebounce(log, 3000);

for(let i = 0 ; i < 10 ; i++){
debouncedLog("Hello"); // Will log "Hello" after 3 seconds only once
}
+

Check my latest Blog Post

How to Publish Your First npm Package: Creating Rainbow Highlight with Utilities

Read Now
Oh My Gawwdd!!!!!!!

Wow you have been viewing my site since 20 seconds!

+
+