Skip to content

Instantly share code, notes, and snippets.

@JenniferFuBook
Last active September 6, 2019 04:34
Show Gist options
  • Save JenniferFuBook/61697bb9b7917af7cecdcb4461b45074 to your computer and use it in GitHub Desktop.
Save JenniferFuBook/61697bb9b7917af7cecdcb4461b45074 to your computer and use it in GitHub Desktop.
Throttle limits the rate at which a function can fire. It can only be invoked once during the limit time window. It is a different control compared to debounce.
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function(...args) {
if (!lastRan) {
func.apply(this, args)
lastRan = Date.now();
} else {
clearTimeout(lastFunc)
lastFunc = setTimeout(() => {
if ((Date.now() - lastRan) >= limit) {
func.apply(this, args)
lastRan = Date.now()
}
}, limit - (Date.now() - lastRan))
}
}
}
// The message, 'Function is actually invoked', will be printed at most once for every 5 seconds during the browser window resizing.
window.addEventListener('resize', throttle(()=>console.log('Function is actually invoked'), 5000));
console.log('Throttle will be called');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment