Skip to content

Instantly share code, notes, and snippets.

@ayushv512
Last active March 3, 2023 16:42
Show Gist options
  • Save ayushv512/a2f963bface38f5e2f6f6bba39bba9b9 to your computer and use it in GitHub Desktop.
Save ayushv512/a2f963bface38f5e2f6f6bba39bba9b9 to your computer and use it in GitHub Desktop.
Throttle in JavaScript
const throttle = (func, limit) => {
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args)
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment