43

How can I add a timeout to the following script? I want it to display text as "Timed Out".

var bustcachevar = 1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects = ""
var rootdomain = "http://" + window.location.hostname
var bustcacheparameter = ""

function ajaxpage(url, containerid) {
    var page_request = false
    if (window.XMLHttpRequest) // if Mozilla, Safari etc
        page_request = new XMLHttpRequest()
    else if (window.ActiveXObject) { // if IE
        try {
            page_request = new ActiveXObject("Msxml2.XMLHTTP")
        } catch (e) {
            try {
                page_request = new ActiveXObject("Microsoft.XMLHTTP")
            } catch (e) {}
        }
    } else
        return false
    document.getElementById(containerid).innerHTML = '<img src="load.gif" border="0"><br><br><strong>Generating Link...</strong>'
    page_request.onreadystatechange = function () {
        loadpage(page_request, containerid)
    }
    if (bustcachevar) //if bust caching of external page
        bustcacheparameter = (url.indexOf("?") != -1) ? "&" + new Date().getTime() : "?" + new Date().getTime()
    page_request.open('GET', url + bustcacheparameter, true)
    page_request.send(null)
}


function loadpage(page_request, containerid) {
    if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1))
        document.getElementById(containerid).innerHTML = page_request.responseText
    else if (page_request.readyState == 4 && (page_request.status == 404 || window.location.href.indexOf("http") == -1))
        document.getElementById(containerid).innerHTML = '<strong>Unable to load link</strong><br>Please try again in a few moments'
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
InvalidSyntax
  • 9,131
  • 20
  • 80
  • 127
  • A very good answer to this question is here: http://stackoverflow.com/questions/1018705/how-to-detect-timeout-on-an-ajax-xmlhttprequest-call-in-the-browser – Jonathan M Aug 26 '11 at 21:11

1 Answers1

105

using the timeout properties of XMLHttpRequest object for example.

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
        alert("ready state = 4");
    }
};

xhr.open("POST", "http://www.service.org/myService.svc/Method", true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.timeout = 4000; // Set timeout to 4 seconds (4000 milliseconds)
xhr.ontimeout = function () { alert("Timed out!!!"); }
xhr.send(json);

the above code works for me!

Cheers

Ulad Kasach
  • 11,558
  • 11
  • 61
  • 87
André Pedroso
  • 1,574
  • 1
  • 17
  • 16
  • 1
    Edited the code: the timeout handler should be set to `ontimeout`, not just `timeout`. (Found this post while searching for the same thing, [MSDN](http://msdn.microsoft.com/en-us/library/ie/cc304105%28v=vs.85%29.aspx) confirms). – Niet the Dark Absol Jan 24 '12 at 21:28
  • @erikvold `timeout`/`ontimeout` are supported also in Firefox, starting from Firefox 12.0: https://developer.mozilla.org/en/xmlhttprequest#Browser_compatibility – jakub.g Jul 05 '12 at 15:14
  • 12
    Just a note for anyone else seeing an intermittant error with XHR and IE10 - the xhr.timeout value must be set after the xhr.open statement. If the timeout value is set before I saw IE10 intermittantly throwing an error. – paj Aug 14 '13 at 07:04
  • note the difference between xhr.timeout and setTimeout. The former is how long the request can take before being terminated. The latter is how long you want the process to wait before executing a particular function. – Magne Sep 25 '14 at 16:25
  • 4
    Be warned that ontimeout event does not get fired until AFTER readyState == 4 is triggered. This is not only non-intuitive, but makes it difficult to create conditional behavior based on whether an upload didn't succeed due to the fact that there was a timeout or not. For example, customizing a user alert as to the reason an upload failed. In my situation I found that I could only accomplish what I wanted with setTimeout. Also, xhr.timeout does not seem to work on Safari as of 2016 – KevinHJ Jun 23 '16 at 01:05
  • @KevinHJ : it seems to me that xhr.status == 0 when timeout (instead of some HTTP response code) – FlorianB Oct 07 '21 at 20:46