我正在使用JavaScript代码编辑器,用户可以在浏览器中编写自己的JavaScript代码并运行它。我需要找到一种突破无限循环的方法。当我得到代码时:
while (1) {
doSomething();
}
我想将代码转换为如下形式:
var start = Date.now();
while (1) {
if (Date.now() - start > 1000) { break; }
doSomething();
}
我偶然发现了Web-Maker which has a function that does exactly this。我无法获得转换传入代码的函数。我尝试过addInfiniteLoopProtection('while (1) doSomething()', { timeout: 1000 })
,但它返回'while (1) doSomething()'
而不是更改代码以摆脱无限循环。
答案 0 :(得分:0)
我找到了loop-protect。独立安装Babel并通过npm进行环路保护:
npm i @babel/standalone loop-protect
然后添加JavaScript代码:
import Babel from '@babel/standalone';
import protect from 'loop-protect';
const timeout = 100;
Babel.registerPlugin('loopProtection', protect(timeout));
const transform = source => Babel.transform(source, {
plugins: ['loopProtection'],
}).code;
transform('while (1) doSomething()')
返回字符串:
var _LP = Date.now();
while (1) {
if (Date.now() - _LP > 100) break;
doSomething();
}