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

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

Leave a Comment