Question

I'm looking for JavaScript code to forcibly1 time out an operation.

FWIW, in other programming environments, what I'm looking for is achieved by setting an asynchronous interrupt signal on a timer right before initiating the operation, and trapping the interrupt signal (this last point is key, since it determines where control will be transferred after the interruption). In pseudo code it looks something like:

alarm = set_alarm(timeout)
try
    operation()
catch timeout
    return
end
clear(alarm)

Is there something like this in JavaScript? If not, is there some other way to achieve the such forcible interruption?


1 By "forcibly" I mean that the methods does not depend on cooperation from the timed-out code. Such cooperation can take the form of built-in time-out parameters, or a global variable whose setting the called code periodically checks to decide whether or not to continue, etc.

Was it helpful?

Solution

Without getting into something like Webworkers, the only thing you can do is have your operation function track how long it's been running and bail out if it has gone on too long.

Of course, this could leave things in an inconsistent state.

If you are trying to process something and it is taking too long, you can use setTimeout to do things in small chunks at a time.

If you are really lucky to be able to target just the latest-and-greatest browsers and ignore IE, Generator Functions can be magic -- but few of us are that lucky.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top