Douglas Gaskell
Douglas Gaskell

Reputation: 10110

Aborting function execution if it's taking too long to run

Can you abort the execution of a JavaScript function if it's taking too long? If so, how?

ie. I call a synchronous doStuff() and if it does not return within an allotted amount of time, it's aborted and execution continues as if it did return.

Upvotes: 1

Views: 1303

Answers (1)

Greg
Greg

Reputation: 8340

You can't do that with synchronous code (unless you exit the synchronous function from the code inside that function). But you can use promises to achieve what you want in an elegant manner. It's like calling a function asynchronously, and since the resolution is asynchronous, it can be interrupted after a timeout. See how promises work on MSDN, on David Walsh blog, and on promisejs. The later also with some examples around interrupting the promise (see the Promise.race code). There is plenty of information on the internet if you search for it.

Upvotes: 3

Related Questions