Skip to content

Instantly share code, notes, and snippets.

@dsherret
Last active June 1, 2016 17:42
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 dsherret/824a94bdd6b68c995eeca8b7d5c70e1e to your computer and use it in GitHub Desktop.
Save dsherret/824a94bdd6b68c995eeca8b7d5c70e1e to your computer and use it in GitHub Desktop.
export class ThrottledQueue {
private isThrottling = false;
private items: (() => void)[] = [];
constructor(private duration: number) {
}
run(item: () => void) {
this.items.push(item);
this.attemptExecute();
}
private attemptExecute() {
if (!this.isThrottling && this.items.length > 0) {
this.execute();
}
}
private execute() {
this.triggerThrottling();
this.runFirstItem();
}
private triggerThrottling() {
this.isThrottling = true;
setTimeout(() => {
this.isThrottling = false;
this.attemptExecute();
}, this.duration);
}
private runFirstItem() {
this.items[0]();
this.items.shift();
}
}
@dsherret
Copy link
Author

dsherret commented Jun 1, 2016

Example use:

let queue = new ThrottledQueue(100);
for (let i = 0; i < 50; i++) {
    queue.run(() => console.log(new Date()));
}

Which will output the date 50 times every 100ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment