Skip to content

Commit

Permalink
Use microtask for autorun if Promise is present.
Browse files Browse the repository at this point in the history
  • Loading branch information
rwjblue committed Jan 17, 2018
1 parent af9934f commit 63ecfbf
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
14 changes: 13 additions & 1 deletion lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ function parseArgs() {
return [target, method, args];
}

const DEFAULT_NEXT = (() => {
if (typeof Promise === 'function') {
const autorunPromise = Promise.resolve();
return (fn) => autorunPromise.then(fn);
}

return (fn) => SET_TIMEOUT(fn, 0);
})();

export default class Backburner {
public static Queue = Queue;

Expand Down Expand Up @@ -103,7 +112,7 @@ export default class Backburner {
let platform = Object.create(null);
platform.setTimeout = _platform.setTimeout || ((fn, ms) => setTimeout(fn, ms));
platform.clearTimeout = _platform.clearTimeout || ((id) => clearTimeout(id));
platform.next = _platform.next || ((fn) => SET_TIMEOUT(fn, 0));
platform.next = _platform.next || DEFAULT_NEXT;
platform.clearNext = _platform.clearNext || platform.clearTimeout;
platform.now = _platform.now || (() => Date.now());

Expand All @@ -114,6 +123,9 @@ export default class Backburner {
};

this._boundAutorunEnd = () => {
// if the autorun was already flushed, do nothing
if (this._autorun === null) { return; }

this._autorun = null;
this.end();
};
Expand Down
18 changes: 17 additions & 1 deletion tests/autorun-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ QUnit.test('autorun', function(assert) {
assert.equal(step++, 0);

bb.schedule('zomg', null, () => {
assert.equal(step, 2);
assert.equal(step++, 2);
setTimeout(() => {
assert.ok(!bb.hasTimers(), 'The all timers are cleared');
done();
Expand Down Expand Up @@ -58,3 +58,19 @@ QUnit.test('autorun (joins next run if not yet flushed)', function(assert) {
two: { count: 1, order: 1 }
});
});

QUnit.test('can be canceled (private API)', function(assert) {
let done = assert.async();
let bb = new Backburner(['zomg']);

assert.ok(!bb.currentInstance, 'precond - The DeferredActionQueues object is lazily instaniated');

bb.schedule('zomg', null, () => {
assert.notOk(true, 'should not flush');
});

assert.ok(bb.currentInstance, 'The DeferredActionQueues object exists');
bb['_cancelAutorun']();

setTimeout(done, 10);
});

0 comments on commit 63ecfbf

Please sign in to comment.