Created
February 4, 2017 15:09
-
-
Save larsch/b1509e7f66fb17b0cc394d02af5985fa to your computer and use it in GitHub Desktop.
Throttled Event Handling in JavaScript
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
/** | |
* 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