Created
April 7, 2013 17:44
-
-
Save tgvashworth/5331538 to your computer and use it in GitHub Desktop.
Debounced callback
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
// Debouce a callback | |
var debounce = (function () { | |
// Save the previously used callbacks and timers | |
var cbs = [], | |
timers = []; | |
// When debounce is called, they're calling this function | |
return function (delay, cb) { | |
// Find or store this callback | |
var cbIndex = cbs.indexOf(cb); | |
if (cbIndex === -1) { | |
cbIndex = cbs.push(cb); | |
} | |
// When the event fires, this function is called | |
return function () { | |
// Save the arguments | |
var args = [].slice.call(arguments); | |
// Clear any current timers and start a new one | |
clearTimeout(timers[cbIndex]); | |
timers[cbIndex] = setTimeout(function () { | |
cb.apply(this, args); | |
}.bind(this), delay); | |
}; | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment