Link to home
Start Free TrialLog in
Avatar of earwig75
earwig75

asked on

Add timeout to getJSON ajax call

I am using the below ajax to get some JSON from an API. Can someone tell me how I can add a timeout to this function? The fail only works if it fails the call right away.

Thank you.

  $.getJSON(foursquareURL).done(function (info) {
    var results = info.response.venues[0];
    if (typeof self.URL === 'undefined') {
      self.URL = '';
    }
    else {
      self.URL = results.url;
    }
    self.street = results.location.formattedAddress[0] || '';
    self.city = results.location.formattedAddress[1] || '';
    self.phone = results.contact.phone || '';
  }).fail(function () {
    $('.list').html('Error.');
  });

Open in new window

Avatar of Swatantra Bhargava
Swatantra Bhargava
Flag of India image

Try Following

var retVal = $.getJSON(foursquareURL).done(function (info) {
    var results = info.response.venues[0];
    if (typeof self.URL === 'undefined') {
      self.URL = '';
    }
    else {
      self.URL = results.url;
    }
    self.street = results.location.formattedAddress[0] || '';
    self.city = results.location.formattedAddress[1] || '';
    self.phone = results.contact.phone || '';
  }).fail(function () {
    $('.list').html('Error.');
  });

setTimeout(function(){ retVal.abort(); }, 2000);

Open in new window

SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of earwig75
earwig75

ASKER

Can I display an error when the time out happens?
Can I display an error when the time out happens?
Did you see my sample?

The error happens in the fail when the timeout occurs.
Thank you!
@earwig75,

I would have split the points between my post and leakim's post. The first post uses setTimeout() which works but is not the best solution in this case when jQuery specifically provides for a timeout.