简体   繁体   中英

How to detect and stop an infinite loop in user-provided JavaScript code?

I am writing an in-browser code editor for games. The editor will allow users to write their own JavaScript files, which are then loaded into the same DOM that the editor is running on. This will allow them to see the game in a canvas element next to the code and update it every time they save.

The editor is aimed at people who are new to JavaSript, and it can be easy to accidentally get an infinite loop. If possible, I want to set up my editor such that if a loop executes too many times or too fast, the loop is broken and a message pops up alerting the user that they have an infinite loop.

This would be ideal for people who are new, because if the entire editor just crashed suddenly, they may not realize what their mistake was and think it was an issue with my editor.

How can I implement fail-safes in my editor which stop infinite loops automatically?

The best way to handle potential infinite loops in user-submitted code is to pre-compile the code to insert monitoring functions inside the code. This is known as instrumenting , and is explained in detail by Codepen .

For example, the following code from a user...:

for (var i = 0;; i++) {
  console.log("hello for loop.");
}

console.log("We'll never reach this line of code");

...would be instrumented like so:

for (var i = 0;; i++) {
    if (window.CP.shouldStopExecution(1)) {
        break;
    }
    console.log('hello for loop.');
}

console.log('finished because we broke out of the loop');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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