Last active
February 22, 2016 13:04
-
-
Save Soreine/96981c07eb334d669036 to your computer and use it in GitHub Desktop.
A custom debouncing function
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
// Returns a function that can't be called more than once per `delay`, | |
// with a maximum delay of `maxDelay`. The returned function can be called | |
// forcefully through its `flush` property | |
function debounce(fn, delay, maxDelay) { | |
var timer; | |
var maxTimer; | |
var args; | |
var clearTimers = function () { | |
if (timer) clearTimeout(timer); | |
if (maxTimer) clearTimeout(maxTimer); | |
}; | |
var doCallFn = function () { | |
clearTimers(); | |
fn.apply(undefined, [].slice(args)); | |
}; | |
var debounced = function () { | |
args = arguments; | |
// Reset the timer | |
if (timer) { | |
clearTimeout(timer); | |
} | |
timer = setTimeout(doCallFn, delay); | |
if (!maxTimer) { | |
maxTimer = setTimeout(doCallFn, maxDelay); | |
} | |
}; | |
// Forces a call | |
debounced.flush = doCallFn; | |
return debounced; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment