Skip to content

Instantly share code, notes, and snippets.

@cagataycali
Created November 22, 2021 12:23
Show Gist options
  • Save cagataycali/05934324cf00584283d0ca6eccfa50a2 to your computer and use it in GitHub Desktop.
Save cagataycali/05934324cf00584283d0ca6eccfa50a2 to your computer and use it in GitHub Desktop.
[JavaScript] Debounce
function debounce(func, wait, immediate) {
let timeout = null;
return function () {
let context = this;
let args = arguments;
const later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
}
const callNow = immediate && !timeout;
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
}
}
// Example
// const handleScroll = debounce(() => console.log(new Date()), 200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment