Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Queue throttle #464

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 42 additions & 3 deletions lib/queue.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ function Queue(concurrency) {
this.processTimeout = 0;
this.throttleCount = 0;
this.throttleInterval = 1000;
this.throttleTimer = null;
this.count = 0;
this.tasks = [];
this.waiting = [];
Expand Down Expand Up @@ -64,7 +65,7 @@ Queue.prototype.add = function (item, factor = 0, priority = 0) {
const task = [item, factor, priority];
const slot = this.count < this.concurrency;
if (!this.paused && slot && this.onProcess) {
this.next(task);
this.execute(task);
return this;
}
let tasks;
Expand Down Expand Up @@ -92,6 +93,15 @@ Queue.prototype.add = function (item, factor = 0, priority = 0) {
return this;
};

// Execute task
// task - <Array>, next task [item, priority]
//
// Returns: <this>
Queue.prototype.execute = function (task) {
if (this.waitTimeout) setTimeout(() => this.next(task), this.waitTimeout);
else this.next(task);
};

// Process next item
// task - <Array>, next task [item, factor, priority]
//
Expand Down Expand Up @@ -143,8 +153,37 @@ Queue.prototype.takeNext = function () {
} else {
tasks = this.tasks;
}
const task = tasks.shift();
if (task) this.next(task);
if (this.throttleCount) {
let shouldStartTask = false;

const startTask = () => {
const available = this.throttleCount - this.count;
if (available > 0) {
const allowed = Math.min(this.concurrency, available);
for (let i = 0; i < allowed; i++) {
const task = this.tasks.shift();
if (task) {
this.execute(task);
}
}
}
};

const delayed = () => {
this.throttleTimer = null;
if (shouldStartTask) startTask();
};

if (!this.throttleTimer) {
this.throttleTimer = setTimeout(delayed, this.throttleInterval);
shouldStartTask = false;
startTask();
}
shouldStartTask = true;
} else {
const task = this.tasks.shift();
this.execute(task);
}
return this;
};

Expand Down