Skip to content

Instantly share code, notes, and snippets.

@zhongyangxun
Last active March 5, 2021 05:13
Show Gist options
  • Save zhongyangxun/676b62f1344c7c3572e40a0dd259ee1f to your computer and use it in GitHub Desktop.
Save zhongyangxun/676b62f1344c7c3572e40a0dd259ee1f to your computer and use it in GitHub Desktop.
JavaScript debounce function.
function debounce(func, wait = 200, immediate) {
let timeout = null;
let context = null;
let args = null;
let previous = null;
let result = null;
function later() {
var passed = Date.now() - previous;
if (passed < wait) {
timeout = setTimeout(later, wait - passed);
} else {
timeout = null;
if (!immediate) func.apply(context, args);
}
}
return function (...rest) {
context = this;
args = rest;
previous = Date.now();
if (!timeout) {
timeout = setTimeout(later, wait);
if (immediate) result = func.apply(context, args);
}
return result;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment