简体   繁体   English

如何检测和停止用户提供的 JavaScript 代码中的无限循环?

[英]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.编辑器将允许用户编写自己的 JavaScript 文件,然后将这些文件加载​​到运行编辑器的同一个 DOM 中。 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.该编辑器面向 JavaSript 的新手,很容易不小心陷入无限循环。 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 .这称为检测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');

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

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