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'
}
1

1 Answer 1

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

6
  • 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 confirms). Jan 24, 2012 at 21:28
  • @erikvold timeout/ontimeout are supported also in Firefox, starting from Firefox 12.0: developer.mozilla.org/en/xmlhttprequest#Browser_compatibility
    – jakub.g
    Jul 5, 2012 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, 2013 at 7: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, 2014 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, 2016 at 1:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.