[英]How to limit the execution time of a function in javascript?
The situation is: 情况是:
User writes some js-code and it should be runned on some data (locally). 用户编写一些js代码,它应该在某些数据(本地)上运行。
But sometimes there are endless loops or recursive calls… That's why I need to limit the execution time of a function but not to edit the function itself (and even if so — should I insert checks after every sequence point? but what about recursive calls?) 但有时会出现无限循环或递归调用...这就是为什么我需要限制函数的执行时间而不是编辑函数本身(即使这样 - 我应该在每个序列点之后插入检查吗?但是递归调用呢? )
Are there any other solutions for this strange problem? 这个奇怪的问题还有其他解决方案吗? Maybe eval can give some parse tree of the code or something like that? 也许eval可以提供一些代码的解析树或类似的东西?
A possible solution is using Web Workers . 可能的解决方案是使用Web Workers 。 A web worker is started in a separate thread and can be terminated. Web工作程序在单独的线程中启动,可以终止。
var worker = new Worker('my_task.js');
...
worker.terminate();
Downside is that not all browsers support Web Workers. 缺点是并非所有浏览器都支持 Web Workers。
Is this in the browser or in node? 这是在浏览器中还是在节点中?
In the browser you can put your code in a 0-second setTimeout
to free up the run loop (and unblock the browser temporarily) 在浏览器中,您可以将代码放在0秒的setTimeout
以释放运行循环(并暂时取消阻止浏览器)
setTimeout(function() {
// your code here
}, 0)
node has something fancier that looks like this and is slightly better: 节点有一些看起来像这样的更好的东西,稍微好一点:
process.nextTick(function() {
// frees up the run loop even faster
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.