Skip to content

Instantly share code, notes, and snippets.

@jbreckmckye
Created April 24, 2019 16:57
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 jbreckmckye/d123a94a1004423e67c79d5dffea2d26 to your computer and use it in GitHub Desktop.
Save jbreckmckye/d123a94a1004423e67c79d5dffea2d26 to your computer and use it in GitHub Desktop.
Grouped throttle function
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