无限循环保护

问题描述 投票:1回答:1

我正在开发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()'而不是更改代码以打破无限循环。

Here's my attempt on codepen

javascript infinite-loop esprima
1个回答
0
投票

我找到了loop-protect。通过npm安装Babel standalone和loop-protect:

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();
}
© www.soinside.com 2019 - 2024. All rights reserved.