Created
April 24, 2019 16:57
-
-
Save jbreckmckye/d123a94a1004423e67c79d5dffea2d26 to your computer and use it in GitHub Desktop.
Grouped throttle function
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
function throttleGroup(fn, count, delay) { | |
let queue = []; | |
let nextDrain = null; | |
function scheduleDrain() { | |
nextDrain = window.setTimeout(drainQueue, delay); | |
} | |
function drainQueue() { | |
const groupSize = Math.min(count, queue.length); | |
for (let i = 0; i < groupSize; i++) { | |
fn.apply(this, ...queue.shift()) | |
} | |
nextDrain = null; | |
if (queue.length) { | |
scheduleDrain(); | |
} | |
} | |
return function(...args) { | |
queue.push([args]); | |
if (!nextDrain) { | |
scheduleDrain(); | |
} | |
} | |
} | |
function sayer(a) { | |
console.log(a, new Date().toLocaleString()) | |
} | |
function manySayer() { | |
const throttledSayer = throttleGroup(sayer, 2, 1000); | |
for (let i = 0; i < 30; i++) { | |
throttledSayer('Hello world! ' + i); | |
} | |
} | |
manySayer(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment