Home > Blockchain >  Stop an unknown function from running after 5 seconds
Stop an unknown function from running after 5 seconds

Time:01-06

Let's say I have a function someFunction() that i don't any control of what inside of it. I wish to run this function for no more than 5 seconds.

I've tried using a setTimeout or setInterval like this:

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.

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.

Thanks a lot!

CodePudding user response:

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. 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.

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. 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). 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).

  • Related