Skip to content

Instantly share code, notes, and snippets.

@mtso
Last active March 1, 2017 06:16
Show Gist options
  • Save mtso/1e59a17ccebcba4123b60951072bb359 to your computer and use it in GitHub Desktop.
Save mtso/1e59a17ccebcba4123b60951072bb359 to your computer and use it in GitHub Desktop.
A JavaScript throttling function.
module.exports = function(callback, threshold) {
var isReady = true;
var onceMore = false;
var context;
var args;
function trigger() {
isReady = false;
callback.apply(context, args);
setTimeout(refresh, threshold);
}
function refresh() {
isReady = true;
if (onceMore) {
trigger();
}
}
return function() {
context = this;
args = arguments;
if (isReady) {
trigger();
} else {
onceMore = true;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment