Last active
November 12, 2022 15:39
-
-
Save beaucharman/e46b8e4d03ef30480d7f4db5a78498ca 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, 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
Here's my version, using TypeScript. It's returning a callback to cancel the timeout, useful if use have to use some cleanup function.
Usage: