Skip to content

Commit

Permalink
Merge pull request #21 from dtex/issue-19
Browse files Browse the repository at this point in the history
Allow tasks to be enqueued out of order
  • Loading branch information
dtex authored Aug 7, 2018
2 parents 19c5968 + 9942cf3 commit ca4ba5e
Show file tree
Hide file tree
Showing 5 changed files with 3,493 additions and 1,778 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
language: node_js
sudo: false
node_js:
- 4
- 6
- 8
- 10
before_script:
- npm install -g grunt-cli
compiler: clang
17 changes: 14 additions & 3 deletions lib/temporal.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ var exportable = new Emitter();
// Object containing callback queues, keys are time in MS
var queue = {};

// Store the last event time
var gLast = Date.now();

// Actively processing queue
var isProcessing = false;

Expand Down Expand Up @@ -50,6 +53,10 @@ function Task(entry) {
this.type = entry.type;
this.time = entry.time;

if (this.later > gLast) {
gLast = this.later;
}

if (!queue[this.later]) {
queue[this.later] = [];
}
Expand Down Expand Up @@ -157,15 +164,13 @@ function processQueue() {
exportable.emit("busy");
}

var scheduled = Object.keys(queue);
var last = scheduled.length && +scheduled[scheduled.length - 1];
var now = getTime();
var entries = [];
var callProcessQueue = true;
var entry, i;

// Nothing scheduled, don't call processQueue again
if (last <= now) {
if (gLast <= now) {
callProcessQueue = false;
}

Expand Down Expand Up @@ -199,6 +204,12 @@ function processQueue() {
// Calculate the next execution time
entry.later = now + entry.time;

// With sub-millisecond wait times, it's conceivable that the clock
// may have passed our next task time so make sure it runs
if (entry.later > gLast) {
gLast = entry.later;
}

// Create a queue entry if none exists
if (!queue[entry.later]) {
queue[entry.later] = [];
Expand Down
Loading

0 comments on commit ca4ba5e

Please sign in to comment.