我正在开发JavaScript代码编辑器,用户可以在浏览器中编写自己的JavaScript代码并运行它。我需要找到一种方法来打破无限循环。当我得到代码时:
while (1) {
doSomething();
}我想将代码转换为如下所示:
var start = Date.now();
while (1) {
if (Date.now() - start > 1000) { break; }
doSomething();
}我偶然发现了网页制作人which has a function that does exactly this。我无法获得函数来转换传入的代码。我尝试过addInfiniteLoopProtection('while (1) doSomething()', { timeout: 1000 }),但它返回'while (1) doSomething()',而不是更改代码以打破无限循环。
发布于 2019-03-08 04:43:15
我找到loop-protect了。通过npm安装Babel单机版和环路保护:
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();
}https://stackoverflow.com/questions/55017794
复制相似问题