views:

158

answers:

2

I apologize if this is a duplicate.

Let's say I have a JavaScript function that calls a web service to pull some data. I use some kind of moving graphic to let the user know it's working. When it is successfully retrieved, I change the graphic to a check mark. Here's my code:

getData: function() {
    $("#button").attr("disabled", "true");

    var params = {
        doRefresh: false,
        method: '/GetData',
        onSuccess: new this.getDataCallback(this).callback,
        onFailure: new this.getDataFailed(this).callback,
        args: { text: $("#getData").val() }
    };

        WebService.invoke(params.method, params.onSuccess, params.onFailure, params.args);

}

What I'd like is after 5 minutes, if this process still has not successfully returned my data, to throw an exception or, better yet, run my function this.getDataFailed(this).callback. Does this seem feasible with JavaScript? I've looked at setTimeout() and setInterval(), and these appear to just delay the execution of a script, whereas I want to literally "timeout" a long running process. Any ideas?

Also, I'm open to any criticism / improvements to my code that would allow for this functionality.

+3  A: 

The way I would do it would look like this (very rough psuedocode):

InvokeWebService
setTimeout

onTimeout:
    cancelInvokation
    DoOtherStuff

onWebServiceCompletion:
    cancelOnTimeout
Anon.
+5  A: 

IE8 offers a timeout property and ontimeout event. These are non-standard however.

I noticed you're using jQuery in some of your example code. jQuery also supports a timeout property for its ajax() method which will execute the error callback after the timeout limit has been reached. You can use the $.ajaxSetup() method to declare the timeout before making any ajax calls:

$.ajaxSetup({
    timeout: 300000
});

If you're not using jQuery to make your requests you can roll your own timeout code:

var xhrTimeout;
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://blah.com/etc", true);
xhr.onreadystatechange = function ()
{
    if (xhr.readyState == 4)
        window.clearTimeout(xhrTimeout);
}
xhr.send();
xhrTimeout = window.setTimeout(function ()
{
    xhr.abort();
    failFunction();
}, 300000); // 5 mins
Andy E
I am using jQuery. So basically I would have to wrap my WebService.invoke call with $.ajax(timeout: 50000, WebService.invoke(...);) Similar to that?
KG
@KG: You can use `$.ajaxSetup()` to set the timeout property which will apply globally to all calls made using `$.ajax()`. See my updated answer.
Andy E
@Andy E I will give this a try, thanks!
KG