Last active
July 15, 2021 21:20
-
-
Save rybarix/39efa394d848a8007d220312c0bd2606 to your computer and use it in GitHub Desktop.
Throttling Javascript events. Throttle dom events or any other events.
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
/** | |
* Throttle function to reduce number of events | |
* coming from event stream | |
* | |
* Useful for reducing number of updates coming from | |
* mousemove events or such. | |
* | |
* @param time - in miliseconds | |
* @param callback - event callback see example below. | |
* | |
* EXAMPLE: | |
* document.addEventListener('mousemove', throttle(100, (event) => { | |
* // Process mousemove event every 100ms | |
* })); | |
* | |
* @author github.com/SandroRybarik | |
* @license MIT | |
*/ | |
const throttle = (time, callback) => { | |
let waiting = false; | |
return (event) => { | |
if (waiting) { | |
return; // discard event | |
} | |
if (!waiting) { | |
callback(event); | |
waiting = true; | |
setTimeout(() => { | |
waiting = false; | |
}, time); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment