Manu
Manu

Reputation: 10934

How to specify timeout in d3 xhr send request

I want to set a timeout value so that if the server does not respond in that particular time frame then the UI should move ahead and not wait for response. I have used the below syntax so far but it does not restrict the UI to listen for the specified time.

      d3.xhr(my_url)
        .header('Content-Type', 'text/xml')
        .header('timeout', 2000)
        .send(this.my_method, my_xmlData, function(error, data) {
        }

I read here that d3 xhr supports timeout feature now. Could anyone please tell me how to use that correctly?

Upvotes: 1

Views: 460

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

Just pass the time (in milliseconds) to timeout (in version 4.x):

.timeout(time)

Here is an example. I'll load a JSON file without timeout:

var url = "https://mysafeinfo.com/api/data?list=englishmonarchs&format=json";

d3.json(url)
  .get(callback);

function callback(data) {
  console.log(data)
}
<script src="https://d3js.org/d3.v4.min.js"></script>

Now the same code, using 1 millisecond in the timeout (a very little time):

var url = "https://mysafeinfo.com/api/data?list=englishmonarchs&format=json";

d3.json(url)
  .timeout(1)
  .get(callback);

function callback(data) {
  console.log(data)
}
<script src="https://d3js.org/d3.v4.min.js"></script>

As you can see 1 millisecond is too little time to get the file, and the callback will return null, as expected.

Upvotes: 2

Related Questions