Skip to content

Instantly share code, notes, and snippets.

@webeli
Forked from beaucharman/throttle.js
Created June 7, 2017 20:35
Show Gist options
  • Save webeli/4d3511ed68931831efbe8d0179b7aa59 to your computer and use it in GitHub Desktop.
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/)
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