Search code examples
javascriptjquerygetjson

Cancel getJSON after pending request x seconds


I am loading an ad network using this code:

$.getJSON('https://server.ads.io/api/v1/decision/?publisher=xx-com&ad_types=text-v1&format=jsonp', function (data) {
    $('#ea-wrapper').html(data.html);
});
    

In a scenario where https://server.ads.io takes too long to load, the browser will wait for the ad ad aeternum. What I am looking for, is a way to cancel the getJSON after, let's say, 3 seconds of waiting with no response. Any idea how to accomplish that?


Solution

  • You can manually abort the request as mentioned in my comment.

    You need to set the getJSON as variable and call that variable in a setTimeout after three seconds to abort the request.

    setTimeout(function(){
      //kill the request
       adRequest.abort()
    }, 3000) //3 seconds
    

    Final code you can try will be like this:

    var adRequest = $.getJSON('https://server.ads.io/api/v1/decision/?publisher=xx-com&ad_types=text-v1&format=jsonp', function(data) {
      $('#ea-wrapper').html(data.html);
    });
    
    setTimeout(function() {
      //kill the request
      addRequest.abort()
    }, 3000)  //3 seconds
    

    If you want to use $.ajax you can use take advantage of native timeout method

    $.ajax({
      url: 'https://server.ads.io/api/v1/decision/?publisher=xx-com&ad_types=text-v1&format=jsonp',
      type: 'GET',
      dataType: 'jsonp',
      success: function(data) {
        $('#ea-wrapper').html(data.html);
      },
      timeout: 3000 //3 seconds
    });