Skip to content

Instantly share code, notes, and snippets.

@ilearnio
Last active September 17, 2021 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilearnio/88fae83a5cfbffd8d489803f2d09e9e5 to your computer and use it in GitHub Desktop.
Save ilearnio/88fae83a5cfbffd8d489803f2d09e9e5 to your computer and use it in GitHub Desktop.
Debounce JS function with leading / fire-first option
function debounce(fn, delay, leading) {
var timeout
var firedAt
return function() {
var args = arguments
function fire () {
firedAt = Date.now()
fn.apply(null, args)
}
if (timeout) clearTimeout(timeout)
if (leading === true) {
var nextFireAt = delay - (Date.now() - firedAt)
if (!firedAt || nextFireAt <= 0) {
fire()
} else {
timeout = setTimeout(fire, nextFireAt)
}
} else {
timeout = setTimeout(fire, delay)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment