简体   繁体   English

如何在javascript中限制函数的执行时间?

[英]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.

相关问题 如何在 javascript 中设置 function 的执行时间限制? - How to set a limit to the execution time of a function in javascript? 如何设置函数执行的限制时间 - How to set a limit time for a function execution 如何计算JavaScript中异步函数的执行时间? - How to calculate the execution time of an async function in JavaScript? 限制jQuery加载函数的执行时间 - limit execution time of jquery load function 如何用微秒精度测量Safari中JavaScript函数的执行时间? - How to measure execution time of JavaScript function in Safari with microsecond precision? 如何知道哪个 JavaScript 函数执行时间最长? - How to know which JavaScript function takes the longest execution time? 如何使用puppeteer获取javascript函数的执行时间? - How to get javascript function execution time using puppeteer? 如何使 JavaScript 按钮点击功能在时间限制后起作用? - How to enabling JavaScript button click function to work after a time limit? 如何限制 javascript function 运行最大。 每天1次 - How to limit a javascript function to run max. 1 time a day 如何限制每隔一定次数执行http-on-modify-request后触发的JavaScript函数的执行? - How to limit the execution of a JavaScript Function triggered after an http-on-modify-request a certain number of times per minute?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM