Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill a Javascript process after a set amount of time

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.

like image 513
karlgrz Avatar asked Feb 19 '10 00:02

karlgrz


1 Answers

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
like image 196
Andy E Avatar answered Oct 27 '22 03:10

Andy E