Last active
September 6, 2019 04:34
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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