Infinite loop protection

1.3k Views Asked by At

I'm working on JavaScript code editor where users can write their own JavaScript code in the browser and run it. 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. 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.

Here's my attempt on codepen

1

There are 1 best solutions below

1
summerjacket On

I found loop-protect. Install Babel standalone and loop-protect through npm:

npm i @babel/standalone loop-protect

Then add the JavaScript code:

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:

var _LP = Date.now();

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