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

I have an asynchronous javascript function. When that function executes, it can end and return data or it runs forever.
I wanted to limit this function execution, so that if the it hangs, I can stop it after a timeout:

  • 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.
  • If it takes more than 10 seconds (in case the function never answers), then I would like to terminate it.

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

5 thoughts on “How to set a limit to the execution time of a function in javascript?”

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

    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.

    Reply

Leave a Comment