简体   繁体   English

5 秒后停止运行未知的 function

[英]Stop an unknown function from running after 5 seconds

Let's say I have a function someFunction() that i don't any control of what inside of it.假设我有一个 function someFunction() ,我无法控制其中的内容。 I wish to run this function for no more than 5 seconds.我希望运行这个 function 不超过 5 秒。

I've tried using a setTimeout or setInterval like this:我试过像这样使用setTimeoutsetInterval

try {
   const timeoutId = setTimeout(() => {
      throw new Error("Time over");
   }, 5000);

   someFunction();
   clearTimeout(timeoutId);
} catch (e) {
   ...
}

The problem in this is that if there is an infinite loop in someFunction() then the timeout will never get called.这里的问题是,如果someFunction()中存在无限循环,则永远不会调用超时。

what's the simplest way to solve this?解决这个问题最简单的方法是什么? I thought about using a worker thread but passing arguments to another thread is problematic in my case.我考虑过使用工作线程,但在我的情况下将 arguments 传递给另一个线程是有问题的。

Thanks a lot!非常感谢!

what's the simplest way to solve this?解决这个问题最简单的方法是什么?

You can't, within the same execution environment.你不能,在同一个执行环境中。 If you don't control what's inside the function, there's no way for you to stop it from your code.如果您不控制 function 中的内容,您将无法从代码中阻止它。 Once you've made the call to someFunction , your code doesn't get control back until that function has run to completion.¹ If it loops infinitely, it loops infinitely.调用someFunction后,直到 function 运行完成,您的代码才能取回控制权。¹如果它无限循环,它就会无限循环。

You could spawn a worker thread or child process that runs the function in a separate environment, which you can then terminate ( 1 , 2 ) after a period of time.可以在单独的环境中生成一个运行 function 的工作线程子进程,然后您可以在一段时间后终止 ( 1 , 2 )。 But within your main environment, you can't do it.但是在你的主要环境中,你不能这样做。


¹ Note that in the case of an async function, "run(s) to completion" means "reaches the point where it returns its promise" (the first await , return [implicit or explicit], or uncaught error). ¹ 请注意,在async function 的情况下,“运行到完成”意味着“到达它返回其承诺的点”(第一个awaitreturn [隐式或显式] 或未捕获的错误)。 So in theory if you had an async function that started something then didn't go into the finite loop until after the first await (say), your code would get an opportunity to run, but if you have no control over the function's code there's nothing you can do from keeping it from continuing again (other than run an infinite loop of your own, which of course you wouldn't want to do).所以理论上,如果你有一个async function 开始了一些事情然后没有 go 进入有限循环直到第一次await (比如)之后,你的代码将有机会运行,但如果你无法控制函数的代码,那么您无法阻止它再次继续(除了运行您自己的无限循环,您当然不想这样做)。

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

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