Skip to content

Instantly share code, notes, and snippets.

@leifoolsen
Last active August 28, 2016 12:57
Show Gist options
  • Save leifoolsen/c29312e0804a871ff84d to your computer and use it in GitHub Desktop.
Save leifoolsen/c29312e0804a871ff84d to your computer and use it in GitHub Desktop.
Debounce limits the rate at which a function can fire.
// Debounce limits the rate at which a function can fire.
// Debouncing ensures that exactly one signal is sent for an event that may be happening several times
// See e.g: http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
// http://davidwalsh.name/javascript-debounce-function
function debounce(fn, treshold, options) {
'use strict';
treshold || (treshold = 250);
options || (options = {});
var timeout;
return function() {
var context = options.scope || this,
args = arguments,
callNow = options.immediate && !timeout,
later = function() {
timeout = null;
if (!options.immediate) fn.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, treshold);
if (callNow) fn.apply(context, args);
};
};
(function(){
var i = 0,
n = 0,
f = debounce( function(x) { ++n; console.log("f(" + x + ") = " + n); }, 250);
var t = setInterval( function () {
if(++i == 200) {
clearInterval(t);
}
f(i);
}, 10);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment