Skip to content

Instantly share code, notes, and snippets.

@larryprice
Created August 13, 2015 12:34
Show Gist options
  • Save larryprice/f83ef2ec4e7a5dd8c020 to your computer and use it in GitHub Desktop.
Save larryprice/f83ef2ec4e7a5dd8c020 to your computer and use it in GitHub Desktop.
mimicing _.throttle
var _ = {};
_.throttle = function (func, wait, options) {
var initial;
return function () {
if (!initial || new Date() - initial >= wait) {
initial = new Date();
func.apply(this, arguments);
}
};
}
var f = function (s) {
console.log(s);
}
var throttledF = _.throttle(f, 10);
var i = 1;
throttledF(i++); // 1
throttledF(i++);
throttledF(i++);
setTimeout(function () {
throttledF(i++); // 4
throttledF(i++);
throttledF(i++);
}, 5);
setTimeout(function () {
throttledF(i++);
throttledF(i++);
throttledF(i++);
}, 10);
setTimeout(function () {
throttledF(i++); // 10
throttledF(i++);
throttledF(i++);
}, 15);
setTimeout(function () {
throttledF(i++); // 13
throttledF(i++);
throttledF(i++);
}, 20);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment