简体   繁体   中英

JavaScript/Ajax: If XMLHttpRequest() fails after x seconds, proceed

[It is important to note: I did my research before hand and I saw similar questions were asked, but yet nothing was suitable for my need.]

I am using the following JavaScript/Ajax code to refresh my iframe ( tracker ) every 120 seconds. If, for some reason the refresh fails (eg no internet connection), it will redirect the page to Tracker2.html .

<script type=text/javascript>
setInterval(function(){
var rq = new XMLHttpRequest();
rq.open('GET', document.getElementById('tracker').src, true);
rq.onreadystatechange = function() {
    if(rq.readyState === 4) {
        if(rq.status === 200) {
        } else {
    window.location.href = "Tracker2.html";
        }
    }
}; 
rq.send(null);
    document.getElementById("tracker").src+="";
},120000);
</script>

My problem is that, using XMLHttpRequest , it takes about 45-60 seconds until it is 'confirmed' there is no internet connection (= failed to refresh the iframe) and ONLY THEN it will redirect to Tracker2.html .

I would like to, ideally, only wait 5 seconds, and IF after 5 seconds, there is no response from the tracker's iframe, then redirect.

Basically, I do not need it to wait 45-60 seconds to realize there is no internet connection - this is an internal network, it only takes half a second to confirm whether there is or there is no connection to the network.

Any help would be greatly appreciated.

You could add a setTimeout inside the setInterval I edited your code.

setInterval(function(){
var rq = new XMLHttpRequest();
rq.open('GET', document.getElementById('tracker').src, true);
rq.onreadystatechange = function() {
    if(rq.readyState === 4) {
        if(rq.status === 200) {
            clearTimeout(cancel);
        } else {
            window.location.href = "Tracker2.html";
        }
    }
}; 
rq.send(null);
var cancel = setTimeout(function(){
    window.location.href = "Tracker2.html";
}, 5000);

    document.getElementById("tracker").src+="";
},120000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM