Skip to content

Instantly share code, notes, and snippets.

@leifoolsen
Last active August 29, 2015 14:17
Show Gist options
  • Save leifoolsen/b721731505c335056368 to your computer and use it in GitHub Desktop.
Save leifoolsen/b721731505c335056368 to your computer and use it in GitHub Desktop.
Throttling is a means by which we can limit the number of times a function can be called in a given period.
// Throttling is a means by which we can limit the number of times a function can be called in a given period.
// Throttling is good for reducing mousemove events to a lesser, manageable rate, for instance.
// See e.g: https://remysharp.com/2010/07/21/throttling-function-calls
function throttle(fn, delay, options) {
'use strict';
delay || (delay = 250);
options || (options = {});
var timeout,
result,
previous = 0;
return function() {
var now = new Date();
if (!previous && options.leading === false) previous = now;
var remaining = delay - (now - previous),
context = options.scope || this,
args = arguments,
later = function() {
previous = options.leading ? new Date() : 0;
timeout = null;
result = fn.apply(context, args);
};
if (remaining <= 0) {
clearTimeout(timeout);
previous = now;
result = fn.apply(context, args);
}
else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
(function(){
var i = 0,
n = 0,
f = throttle( function(x) { ++n; console.log("f(" + x + ") # " + n); }, 250);
var t = setInterval( function () {
f(i);
if(++i == 200) {
clearInterval(t);
console.log("throttle executed " + n + " times in " + i*10 + "ms");
}
}, 10);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment