Skip to content

Instantly share code, notes, and snippets.

@tgvashworth
Created April 7, 2013 17:44
Show Gist options
  • Save tgvashworth/5331538 to your computer and use it in GitHub Desktop.
Save tgvashworth/5331538 to your computer and use it in GitHub Desktop.
Debounced callback
// 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