简体   繁体   English

如何在 javascript 中设置 function 的执行时间限制?

[英]How to set a limit to the execution time of a function in javascript?

I have an asynchronous javascript function.我有一个异步 javascript function。 When that function executes, it can end and return data or it runs forever.当 function 执行时,它可以结束并返回数据,也可以永远运行。 I wanted to limit this function execution, so that if the it hangs, I can stop it after a timeout:我想限制这个 function 执行,这样如果它挂起,我可以在超时后停止它:

  • If it takes less than 10 seconds running (for example, it takes 4 seconds to complete), then it doesn't have to wait 6 seconds to execute the next instructions.如果运行时间少于 10 秒(例如,需要 4 秒完成),则不必等待 6 秒即可执行下一条指令。
  • If it takes more than 10 seconds (in case the function never answers), then I would like to terminate it.如果需要超过 10 秒(以防 function 永远不会回答),那么我想终止它。

Is there any way to do this without using setTimeout() (because I don't want to wait if the function ends its execution before the timeout)?有没有办法在不使用 setTimeout() 的情况下做到这一点(因为如果 function 在超时之前结束执行,我不想等待)?

If you are doing API calls, a library like axios provides timeouts options如果您正在执行 API 调用,则像axios这样的库会提供超时选项

import axios from axios ;

axios
.get(‘url’, {timeout: 3000})
.then((res) => console.log(res))
.catch((err) => console.log(err))

Otherwise I think, you can clear/kill timeout before it ends: https://stackoverflow.com/a/452007/10691892否则我认为,您可以在超时结束之前清除/终止超时: https://stackoverflow.com/a/452007/10691892

There is no general way to do this.没有通用的方法可以做到这一点。

The closest you could come would be to create a promise and reject it with a setTimeout (which you wanted to avoid) but that would still leave the asynchronous process running.您最接近的方法是创建一个 promise 并使用setTimeout (您想避免)拒绝它,但这仍然会使异步进程继续运行。

Some asynchronous functions have built-in features for configuring a timeout on them, but they are specific to the particular API and not a general solution.一些异步函数具有用于配置超时的内置功能,但它们特定于特定的 API,而不是通用解决方案。

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

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