-
-
Save webeli/4d3511ed68931831efbe8d0179b7aa59 to your computer and use it in GitHub Desktop.
An ES6 implementation of the throttle function. "Throttling enforces a maximum number of times a function can be called over time. As in 'execute this function at most once every 100 milliseconds.'" - CSS-Tricks (https://css-tricks.com/the-difference-between-throttling-and-debouncing/)
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(callback, wait, context = this) { | |
let timeout = null | |
let callbackArgs = null | |
const later = () => { | |
callback.apply(context, callbackArgs) | |
timeout = null | |
} | |
return function() { | |
if (!timeout) { | |
callbackArgs = arguments | |
timeout = setTimeout(later, wait) | |
} | |
} | |
} | |
/** | |
* Normal event | |
* event | | | | |
* time ---------------- | |
* callback | | | | |
* | |
* Call search at most once per 300ms while keydown | |
* keydown | | | | | |
* time ----------------- | |
* search | | | |
* |300| |300| | |
*/ | |
/** usage | |
const handleKeydown = throttle((e) => { | |
console.log(e.target.value) | |
}, 300) | |
input.addEventListener('keydown', handleKeydown) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment