Expand my Community achievements bar.

SOLVED

calculate request timeout in js

Avatar

Level 5

Hi, 

 

I have got the requirement to set maximum timeout in my ajax call.

 

10Mbps = 1mB/s upload ... 1GB file = 14min upload * 2 = 28 min 
10Mbps = 1mB/s upload ... 500MB file = 7min upload * 2 = 14 min 
10Mbps = 1mB/s upload ... 5MB file = 4 sec upload * 2 = 8 sec 

 

How can I get the timeout using the network speed and the file size?

 

Thank you

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

@keerthana_hn 

The XMLHttpRequest.timeout property is an unsigned long representing the number of milliseconds a request can take before automatically being terminated. The default value is 0, which means there is NO_TIMEOUT

 

Also, while your computer request for a download, and the server responds with downloadable content, then you wouldn't get a timeout from your AJAX request. Remember, the purpose of a timeout is to prevent a device from endlessly waiting for a sever to respond.

 

However, if you would like to add a timeout, your request would look something like this:

 

 

var xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);

xhr.timeout = 3000; // time in milliseconds, 3 seconds

xhr.onload = function () {
  // Request finished. Do processing here.
};

xhr.ontimeout = function (e) {
  // XMLHttpRequest timed out. Do something here.
};

xhr.send(null);

 

 

JQUERY would look something like this:

 

 

$.ajax({
    url: "/server",
    error: function(){
        // will fire when timeout is reached
    },
    success: function(){
        //do something
    },
    timeout: 3000  // time in milliseconds, 3 seconds
});

 

 

 

View solution in original post

1 Reply

Avatar

Correct answer by
Community Advisor

@keerthana_hn 

The XMLHttpRequest.timeout property is an unsigned long representing the number of milliseconds a request can take before automatically being terminated. The default value is 0, which means there is NO_TIMEOUT

 

Also, while your computer request for a download, and the server responds with downloadable content, then you wouldn't get a timeout from your AJAX request. Remember, the purpose of a timeout is to prevent a device from endlessly waiting for a sever to respond.

 

However, if you would like to add a timeout, your request would look something like this:

 

 

var xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);

xhr.timeout = 3000; // time in milliseconds, 3 seconds

xhr.onload = function () {
  // Request finished. Do processing here.
};

xhr.ontimeout = function (e) {
  // XMLHttpRequest timed out. Do something here.
};

xhr.send(null);

 

 

JQUERY would look something like this:

 

 

$.ajax({
    url: "/server",
    error: function(){
        // will fire when timeout is reached
    },
    success: function(){
        //do something
    },
    timeout: 3000  // time in milliseconds, 3 seconds
});