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

家住魔仙堡 提交于 2020-08-27 07:19:19

问题


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?


回答1:


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');


来源:https://stackoverflow.com/questions/43948315/how-to-detect-and-stop-an-infinite-loop-in-user-provided-javascript-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!