Clear the stack if onmessage is called before the previous invocation finishes

This commit is contained in:
Steve Gravrock
2017-05-16 14:06:46 -07:00
parent 5ac3e21abb
commit b9adc76dc7
2 changed files with 33 additions and 1 deletions

View File

@@ -37,6 +37,27 @@ describe("ClearStack", function() {
expect(called).toBe(true);
});
it("calls setTimeout when onmessage is called recursively", function() {
var fakeChannel = {
port1: {},
port2: { postMessage: function() { fakeChannel.port1.onmessage(); } }
},
setTimeout = jasmine.createSpy('setTimeout'),
global = {
MessageChannel: function() { return fakeChannel; },
setTimeout: setTimeout,
},
clearStack = jasmineUnderTest.getClearStack(global),
fn = jasmine.createSpy("second clearStack function");
clearStack(function() {
clearStack(fn);
});
expect(fn).not.toHaveBeenCalled();
expect(setTimeout).toHaveBeenCalledWith(fn, 0);
});
it("falls back to setTimeout", function() {
var setTimeout = jasmine.createSpy('setTimeout').and.callFake(function(fn) { fn() }),
global = { setTimeout: setTimeout },

View File

@@ -4,11 +4,22 @@ getJasmineRequireObj().clearStack = function(j$) {
head = {},
tail = head;
var taskRunning = false;
channel.port1.onmessage = function() {
head = head.next;
var task = head.task;
delete head.task;
task();
if (taskRunning) {
global.setTimeout(task, 0);
} else {
try {
taskRunning = true;
task();
} finally {
taskRunning = false;
}
}
};
return function clearStack(fn) {