Skip to content

Commit

Permalink
Merge pull request #647 from share/next-tick
Browse files Browse the repository at this point in the history
⚡️ Remove artificial 4ms `nextTick()` delay when running in a browser
  • Loading branch information
alecgibson authored Apr 2, 2024
2 parents 5d88b87 + 57e0045 commit 8ba28c5
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
2 changes: 2 additions & 0 deletions .mocharc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ reporter: spec
check-leaks: true
recursive: true
file: test/setup.js
globals:
- MessageChannel # Set/unset to test nextTick()
15 changes: 13 additions & 2 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,20 @@ exports.nextTick = function(callback) {
args[i - 1] = arguments[i];
}

setTimeout(function() {
if (typeof MessageChannel === 'undefined') {
return setTimeout(triggerCallback);
}

var channel = new MessageChannel();
channel.port1.onmessage = function() {
triggerCallback();
channel.port1.close();
};
channel.port2.postMessage('');

function triggerCallback() {
callback.apply(null, args);
});
}
};

exports.clone = function(obj) {
Expand Down
33 changes: 33 additions & 0 deletions test/util-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,39 @@ describe('util', function() {
});
expect(called).to.be.false;
});

describe('without MessageChannel', function() {
var _MessageChannel;

before(function() {
_MessageChannel = global.MessageChannel;
delete global.MessageChannel;
});

after(function() {
global.MessageChannel = _MessageChannel;
});

it('uses a different ponyfill', function(done) {
expect(process.nextTick).to.be.undefined;

util.nextTick(function(arg1, arg2, arg3) {
expect(arg1).to.equal('foo');
expect(arg2).to.equal(123);
expect(arg3).to.be.undefined;
done();
}, 'foo', 123);
});

it('calls asynchronously', function(done) {
var called = false;
util.nextTick(function() {
called = true;
done();
});
expect(called).to.be.false;
});
});
});
});
});

0 comments on commit 8ba28c5

Please sign in to comment.