Skip to content

Instantly share code, notes, and snippets.

@mflisikowski
Forked from beaucharman/throttle.js
Created May 12, 2020 05:46
Show Gist options
  • Save mflisikowski/1aac5ad4baf64598c0f2a479ae10c9c4 to your computer and use it in GitHub Desktop.
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/)
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