-
-
Save mflisikowski/1aac5ad4baf64598c0f2a479ae10c9c4 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 hidden or 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, immediate = false) { | |
let timeout = null | |
let initialCall = true | |
return function() { | |
const callNow = immediate && initialCall | |
const next = () => { | |
callback.apply(this, arguments) | |
timeout = null | |
} | |
if (callNow) { | |
initialCall = false | |
next() | |
} | |
if (!timeout) { | |
timeout = setTimeout(next, wait) | |
} | |
} | |
} | |
/** | |
* Normal event | |
* event | | | | |
* time ---------------- | |
* callback | | | | |
* | |
* Call search at most once per 300ms while keydown | |
* keydown | | | | | |
* time ----------------- | |
* search | | | |
* |300| |300| | |
*/ | |
const input = document.getElementById('id') | |
const handleKeydown = throttle((arg, event) => { | |
console.log(`${event.type} for ${arg} has the value of: ${event.target.value}`) | |
}, 300) | |
input.addEventListener('keydown', (event) => { | |
handleKeydown('input', event) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment