2

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

summerjacket
  • 31
  • 1
  • 7

1 Answers1

1

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();
}
summerjacket
  • 31
  • 1
  • 7
  • instead of this shouldn't you be monitoring the thread for resource consumption? what if the user wants to run an infinite loop with low consumption(like pinging a website periodically), your compiler will completely disallow that usecase - or make a savvy user use recursive loops instead – Karan Harsh Wardhan Mar 08 '19 at 07:42