简体   繁体   English

无限回路保护

[英]Infinite loop protection

I'm working on JavaScript code editor where users can write their own JavaScript code in the browser and run it. 我正在使用JavaScript代码编辑器,用户可以在浏览器中编写自己的JavaScript代码并运行它。 I need to find a way to break out of infinite loops. 我需要找到一种突破无限循环的方法。 When I am given the code: 当我得到代码时:

while (1) {
    doSomething();
}

I want to transform the code to something like this: 我想将代码转换为如下形式:

var start = Date.now();
while (1) {
    if (Date.now() - start > 1000) { break; }
    doSomething();
}

I stumbled upon Web-Maker, which has a function that does exactly this . 我偶然发现了Web-Maker, 它的功能可以做到这一点 I couldn't get the function to transform the code passed in. I've tried addInfiniteLoopProtection('while (1) doSomething()', { timeout: 1000 }) but it returns 'while (1) doSomething()' instead of changing the code to break out of the infinite loop. 我无法获得转换传入代码的函数。我尝试了addInfiniteLoopProtection('while (1) doSomething()', { timeout: 1000 })但它返回'while (1) doSomething()'而不是更改代码以打破无限循环。

Here's my attempt on codepen 这是我对Codepen的尝试

I found loop-protect . 我发现了循环保护 Install Babel standalone and loop-protect through npm: 独立安装Babel并通过npm进行环路保护:

npm i @babel/standalone loop-protect

Then add the JavaScript code: 然后添加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()') returns the string: transform('while (1) doSomething()')返回字符串:

var _LP = Date.now();

while (1) {
  if (Date.now() - _LP > 100) break;
  doSomething();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM