Last active
November 23, 2022 18:23
-
-
Save Dodotree/bd8e1752dda7b6b293b46016293b309e to your computer and use it in GitHub Desktop.
Minimalistic JS throttle function to limit calls to any callback function to "once per Nms", most useful with N between 100-300. Can be used on the back end too depending on time delay functions available.
This file contains hidden or 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
| const throttle = (delayFunc, cancelFunc) => (callback, delay) => { | |
| let lastFunc | |
| let lastExecTime | |
| return function (...args) { | |
| const context = this | |
| const elapsed = Date.now() - lastExecTime | |
| function execCallback () { | |
| lastExecTime = Date.now() | |
| callback.apply(context, args) | |
| } | |
| if (!lastExecTime) { | |
| execCallback() | |
| } else { | |
| cancelFunc(lastFunc) | |
| if (elapsed >= delay) { | |
| execCallback() | |
| } else { | |
| lastFunc = delayFunc(execCallback, delay - elapsed) | |
| } | |
| } | |
| } | |
| } | |
| const throttleTout = throttle(setTimeout, clearTimeout) | |
| // alternative can be or similar throttle(requestAnimationFrame, cancelAnimationFrame) | |
| // Example | |
| // area.addEventListener("mousemove", throttleTout(myCallBack("something"), 200)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment