-
-
Save MonaAghili/267543c1876a115e8da82be9477bcdb1 to your computer and use it in GitHub Desktop.
Callback throttler
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
| let timeout = null; | |
| let requestCount = 0; | |
| let queue = []; | |
| function schedule(limit) { | |
| if (!timeout) { | |
| timeout = setTimeout(() => throttleQueue(limit), 1000) | |
| } | |
| } | |
| function throttleQueue(limit) { | |
| timeout = null; | |
| requestCount = 0; | |
| while (requestCount < limit) { | |
| let callback = queue.pop(); | |
| if (callback) { | |
| schedule(limit) | |
| callback(); | |
| ++requestCount; | |
| } else { | |
| break | |
| } | |
| } | |
| } | |
| /** | |
| * Returns a function that will throttle | |
| * callbacks to the limit per second | |
| **/ | |
| function throttle(limit) { | |
| return function(callback) { | |
| if (requestCount >= limit) { | |
| schedule(limit) | |
| queue = [callback, ...queue] | |
| } else { | |
| ++requestCount | |
| callback() | |
| } | |
| } | |
| } | |
| // Request will be fired max 2 per second | |
| const request = throttle(2) | |
| request(() => console.log("1")) | |
| request(() => console.log("2")) | |
| request(() => console.log("3")) | |
| request(() => console.log("4")) | |
| request(() => console.log("5")) | |
| request(() => console.log("6")) | |
| request(() => console.log("7")) | |
| request(() => console.log("8")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment