Skip to content

Instantly share code, notes, and snippets.

@rybarix
Last active July 15, 2021 21:20
Show Gist options
  • Save rybarix/39efa394d848a8007d220312c0bd2606 to your computer and use it in GitHub Desktop.
Save rybarix/39efa394d848a8007d220312c0bd2606 to your computer and use it in GitHub Desktop.
Throttling Javascript events. Throttle dom events or any other events.
/**
* 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