Search code examples
javascriptjqueryajaxtimeoutgetscript

Add a timeout to getScript()


I'm using the getScript() JQuery method but could really do with adding a timeout. Some scripts don't come back as failed for a good 6-8 seconds, which is too long.

Is this possible?

I've searched a bit and no solutions have been forthcoming.

Something like:

$.getScript(a + "/myspeed/MySpeedServer/mss/js")
        .done(function() {
            //do stuff
        })
         .fail(function() {
            //do stuff
        });
         .timeout(2000)

Solution

  • $.getScript is simply a wrapper around $.ajax(). Hence, you could use $.ajax() with the timeout option as below.

    $.ajax({
        url: url,
        dataType: "script",
        timeout: 2 * 1000
    }).done(function() {
        //do stuff
    })
    .fail(function() {
        //do stuff
    });
    

    A note from the doc: In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.

    You may also use the abort() method as stated here.