Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Modifies input code to do the following:
executing loop should be broken
* Injects into `for`, `while`, and `do-while` loops a call to `loopBreaker()`

The loop is considered likely-infinite if the following two conditions hold:
The loop is considered likely-infinite if either of the following two conditions is met:

* The loop has executed at least ten thousand times
* The loop has been running for at least one second of wall time
Expand All @@ -60,7 +60,7 @@ var __loopBreaker = (function() {
return function() {
startTime || (startTime = Date.now());
count += 1;
if (count > 10000 && (Date.now() - startTime > 1000)) {
if (count > 10000 || (Date.now() - startTime > 1000)) {
throw new Error("Loop Broken!");
}
};
Expand Down
8 changes: 7 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,13 @@ const loopBreaker = recast.parse(`var __loopBreaker = (function() {
}

loop.count += 1;
if (loop.count > 10000 && (Date.now() - loop.startTime > 1000)) {
if (loop.count % 100 === 0) {
// Date math is slow, so only check every 100 loops
if (Date.now() - loop.startTime > 1000) {
throw new Error("Loop Broken!");
}
}
if (loop.count > 10000) {
throw new Error("Loop Broken!");
}
},
Expand Down
8 changes: 8 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ testBrokenLoop('do-while with body', (c) => {
} while (c());
});

testBrokenLoop('non-infinite slow code execution', () => {
const testStartTime = Date.now() + 2000;
function checkDate() {
return Date.now() - testStartTime < 2000;
}
while (checkDate()) void(0);
});

function testBrokenLoop(message, fn) {
test(message, (assert) => {
const startTime = Date.now();
Expand Down