Skip to content

Instantly share code, notes, and snippets.

@lexuschert
Created September 26, 2019 09:14
Show Gist options
  • Save lexuschert/35085075f6a73220b9b9cf58bad5d2fb to your computer and use it in GitHub Desktop.
Save lexuschert/35085075f6a73220b9b9cf58bad5d2fb to your computer and use it in GitHub Desktop.
throttle
function throttle(func, ms) {
let isThrottled = false,
savedArgs,
savedThis;
function wrapper() {
if (isThrottled) { // (2)
savedArgs = arguments;
savedThis = this;
return;
}
func.apply(this, arguments); // (1)
isThrottled = true;
setTimeout(function() {
isThrottled = false; // (3)
if (savedArgs) {
wrapper.apply(savedThis, savedArgs);
savedArgs = savedThis = null;
}
}, ms);
}
return wrapper;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment