diff --git a/README.md b/README.md index b3ff786..dff856a 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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!"); } }; diff --git a/src/index.js b/src/index.js index c0f4f19..19c14ef 100644 --- a/src/index.js +++ b/src/index.js @@ -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!"); } }, diff --git a/test/index.js b/test/index.js index 595fd6f..8f0e815 100644 --- a/test/index.js +++ b/test/index.js @@ -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();