5

I have a JavaScript function to call ajax. Now I need to add time out in this function like while calling service took more than defile time ajax call should time out and display a default message. I don't want to use Jquery in it.

here is my code:

AJAX = function (url, callback, params) {
        var dt = new Date();
        url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime();
        if (url.indexOf('callback=') == -1) {
            ajaxCallBack(url, function () {
                if (this.readyState == 4 && this.status == 200) {
                    if (callback) {
                        if (params) {
                            callback(this.responseText, params);
                        } else {
                            callback(this.responseText);
                        }
                    }
                }
            });
        } else {
            var NewScript = d.createElement("script");
            NewScript.type = "text/javascript";
            NewScript.src = url + '&_' + Math.random();
            d.getElementsByTagName('head')[0].appendChild(NewScript);
        }
    },
    ajaxCallBack = function (url, callback) {
        var xmlhttp;
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = callback;
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }
Yogendra
  • 2,139
  • 3
  • 14
  • 27

3 Answers3

2

Here's an example of how you can handle a timeout:

var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://www.example.com", true);

xmlHttp.onreadystatechange=function(){
   if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      clearTimeout(xmlHttpTimeout); 
      alert(xmlHttp.responseText);
   }
}
// Now that we're ready to handle the response, we can make the request
xmlHttp.send("");
// Timeout to abort in 5 seconds
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000);
function ajaxTimeout(){
   xmlHttp.abort();
   alert("Request timed out");
}

In IE8, You can add a timeout event handler to the XMLHttpRequest object.

var xmlHttp = new XMLHttpRequest();
xmlHttp.ontimeout = function(){
  alert("request timed out");
}

Use a javascript framework to do this though, i don't know why you're not using one, do you like uneccesary work? :)

Dan Hall
  • 1,474
  • 2
  • 18
  • 43
  • Thanks you for your help...but it not working in my code as shown above...can you please alter my code.... – Yogendra Dec 21 '15 at 10:42
2

If you want to simply add timeout, You can add it in the first function in three places:

        setTimeout(function() {callback(this.responseText, params)}, 1000)

And your callback will execute around 1s later. The second palce is second call of callback.

Third place that i would suggest is to wrap this function like above:

        ajaxCallBack(url, function () {
            if (this.readyState == 4 && this.status == 200) {
                if (callback) {
                    if (params) {
                        callback(this.responseText, params);
                    } else {
                        callback(this.responseText);
                    }
                }
            }
        });

Usually when i get in to testing internet connection i rather add throttling in the chrome developer tools like this:

enter image description here

Here is your code with first approach:

        AJAX = function (url, callback, params) {
                var dt = new Date();
                url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime();
                if (url.indexOf('callback=') == -1) {
                    ajaxCallBack(url, function () {
                        if (this.readyState == 4 && this.status == 200) {
                            if (callback) {
                                if (params) {
                                    console.log(new Date());
                                    setTimeout(function() {callback(this.responseText, params)}, 2000);
                                } else {
                                    console.error((new Date()).getSeconds());
                                    setTimeout(function() {callback(this.responseText)}, 2000);
                                }
                            }
                        }
                    });
                } else {
                    var NewScript = d.createElement("script");
                    NewScript.type = "text/javascript";
                    NewScript.src = url + '&_' + Math.random();
                    d.getElementsByTagName('head')[0].appendChild(NewScript);
                }
            },
        ajaxCallBack = function (url, callback) {
                var xmlhttp;
                if (window.XMLHttpRequest) {
                    xmlhttp = new XMLHttpRequest();
                } else {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.onreadystatechange = callback;
                xmlhttp.open("GET", url, true);
                xmlhttp.send();
        }

        AJAX('http://ip.jsontest.com/', function() {console.error((new Date()).getSeconds()); });
Piotr Łużecki
  • 1,031
  • 4
  • 17
  • 33
1

Maybe the answer to this question will help. Timeout XMLHttpRequest

since from what i understand you need to set timeout for xmlhttprequest, you can use xmlhttp.timeout = /*some number*/

Community
  • 1
  • 1
Or Yaniv
  • 571
  • 4
  • 11
  • Thanks you for your help...but it not working in my code as shown above...can you please alter my code.... – Yogendra Dec 21 '15 at 10:42