function getNames(){
// some code
}
This function can be done in one second, but sometimes it freezes itself and html block on the page (ajax inside) on infinite time.
I would like to have time limit for this function. If it doesn't finish in ten seconds, then abort it.
How to do this?
This is really easy with jQuery 1.5’s deferred promises.
The following example creates a Deferred and sets two timer-based functions to either resolve or reject the Deferred after a random interval. Whichever one fires first “wins” and will call one of the callbacks. The second timeout has no effect since the Deferred is already complete (in a resolved or rejected state) from the first timeout action.
You can easily modify this example to suit your needs:
If it is the function itself that's grinding away, just set a timer and either
return
orthrow
if it exceeds your maximum time period.If, on the other hand, if the delay is caused by the AJAX request not returning, and you are using
$.ajax()
, you can always set thetimeout
setting. It should kill the request. Note that you need to avoid relying on thesuccess
callback, since it only gets called if the request succeeds. Instead, usecomplete
callback to watch for failures. It will tell you if an error occurred. According to the documentation, this is available in 1.4 onwards. I'm not sure about pre-1.4, but I think it worked in 1.3 as well.As suggested above, you can go with Web Workers if //some code is something that might take a long time sometimes (like waiting for large amounts of information from a slow server). That will allow background processing without locking the main page. Note that not all browsers support it yet.
You can find a nice introduction here.