Skip to content

Commit

Permalink
Add flag for approaching infinite loop
Browse files Browse the repository at this point in the history
Use a flag when approaching infinite loop detection which will enable
an error object to be attached to the job, which can then be used for
generating the stack output.
  • Loading branch information
alistairjcbrown committed May 17, 2020
1 parent 8e38995 commit 033e9fb
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions src/fake-timers-src.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,18 @@ function withGlobal(_global) {
var NativeDate = _global.Date;
var uniqueTimerId = 1;

var isNearInfiniteLimit = false;

function checkIsNearInfiniteLimit(clock, i) {
if (clock.loopLimit && i === clock.loopLimit - 1) {
isNearInfiniteLimit = true;
}
}

function resetIsNearInfiniteLimit() {
isNearInfiniteLimit = false;
}

function isNumberFinite(num) {
if (Number.isFinite) {
return Number.isFinite(num);
Expand Down Expand Up @@ -275,10 +287,13 @@ function withGlobal(_global) {
for (var i = 0; i < clock.jobs.length; i++) {
var job = clock.jobs[i];
job.func.apply(null, job.args);

checkIsNearInfiniteLimit(clock, i);
if (clock.loopLimit && i > clock.loopLimit) {
throw getInfiniteLoopError(clock.loopLimit, job);
}
}
resetIsNearInfiniteLimit();
clock.jobs = [];
}

Expand All @@ -287,7 +302,9 @@ function withGlobal(_global) {
throw new Error("Callback must be provided to timer calls");
}

timer.error = new Error();
if (isNearInfiniteLimit) {
timer.error = new Error();
}

timer.type = timer.immediate ? "Immediate" : "Timeout";

Expand Down Expand Up @@ -790,7 +807,7 @@ function withGlobal(_global) {
return enqueueJob(clock, {
func: func,
args: Array.prototype.slice.call(arguments, 1),
error: new Error()
error: isNearInfiniteLimit ? new Error() : null
});
};

Expand Down Expand Up @@ -1085,15 +1102,18 @@ function withGlobal(_global) {
runJobs(clock);
for (i = 0; i < clock.loopLimit; i++) {
if (!clock.timers) {
resetIsNearInfiniteLimit();
return clock.now;
}

numTimers = keys(clock.timers).length;
if (numTimers === 0) {
resetIsNearInfiniteLimit();
return clock.now;
}

clock.next();
checkIsNearInfiniteLimit(clock, i);
}

var excessJob = firstTimer(clock);
Expand All @@ -1114,13 +1134,15 @@ function withGlobal(_global) {
var numTimers;
if (i < clock.loopLimit) {
if (!clock.timers) {
resetIsNearInfiniteLimit();
resolve(clock.now);
return;
}

numTimers = Object.keys(clock.timers)
.length;
if (numTimers === 0) {
resetIsNearInfiniteLimit();
resolve(clock.now);
return;
}
Expand All @@ -1130,6 +1152,7 @@ function withGlobal(_global) {
i++;

doRun();
checkIsNearInfiniteLimit(clock, i);
return;
}

Expand Down

0 comments on commit 033e9fb

Please sign in to comment.