Skip to content

Instantly share code, notes, and snippets.

@larsch
Created February 4, 2017 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larsch/b1509e7f66fb17b0cc394d02af5985fa to your computer and use it in GitHub Desktop.
Save larsch/b1509e7f66fb17b0cc394d02af5985fa to your computer and use it in GitHub Desktop.
Throttled Event Handling in JavaScript
/**
* Attach an event listener to an object. Invokes the handle()
* callback on every event, and the apply() handler eventually, but
* with at least 'delay' milliseconds between each invokation.
*/
function addThrottledEventHandler(elem, event, handle, apply, delay) {
let nextApply = performance.now();
let timerId = null;
function invokeApply() { apply(); timerId = null; }
elem.addEventListener(event, (ev) => {
if (handle !== null)
handle(ev);
let now = performance.now();
if (now < nextApply) {
if (timerId === null) {
timerId = setTimeout(invokeApply, nextApply - now);
nextApply += delay;
}
} else {
apply();
nextApply = now + delay;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment