Last active
September 17, 2021 04:19
-
-
Save ilearnio/88fae83a5cfbffd8d489803f2d09e9e5 to your computer and use it in GitHub Desktop.
Debounce JS function with leading / fire-first option
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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