16

When making a call out to the yahoo web service (http://boss.yahooapis.com/ysearch) to return a data set, is it possible to set a timeout and exit the routine once its elapsed?

jQuery.getJSON("http://boss.yahooapis.com/ysearch/...etc",
        function (data) {
              //result set here
            });
Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
Scott B
  • 38,833
  • 65
  • 160
  • 266

4 Answers4

18

You can use the timeout option

http://api.jquery.com/jQuery.ajax/

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback,
  timeout: 3000 //3 second timeout
});
Galen
  • 29,976
  • 9
  • 71
  • 89
15
 $.ajax({ 
  url: url, 
  dataType: 'json', 
  data: data, 
  success: callback, 
  timeout: 3000 //3 second timeout, 
  error: function(jqXHR, status, errorThrown){   //the status returned will be "timeout" 
     //do something 
  } 
}); 
anson chow
  • 151
  • 1
  • 2
7
    function testAjax() {
        var params = "test=123";
        var isneedtoKillAjax = true; // set this true

        // Fire the checkajaxkill method after 10 seonds
        setTimeout(function() {
            checkajaxkill();
        }, 10000); // 10 seconds                

        // For testing purpose set the sleep for 12 seconds in php page 

        var myAjaxCall = jQuery.getJSON('index2.php', params, function(data, textStatus){               
            isneedtoKillAjax = false; // set to false
            // Do your actions based on result (data OR textStatus)
        }); 

        function checkajaxkill(){

            // Check isneedtoKillAjax is true or false, 
            // if true abort the getJsonRequest

            if(isneedtoKillAjax){
                myAjaxCall.abort();
                alert('killing the ajax call');                 
            }else{
                alert('no need to kill ajax');
            }
        }
    }
Community
  • 1
  • 1
Mahesh
  • 143
  • 2
  • 16
  • I like the creativeness of this answer. I actually didn't know I could abort a getJSON call that way so thank you. This worked for our app. – uadrive May 21 '14 at 14:56
0

The timeout option proposed by Galen is the best way. If you want an alternate method, you could record the time when the request was initiated and, in your callback, compare it to the current time. Ignore the result if a certain amount of time has elapsed. Of course this would not cancel the request.

Chris Laplante
  • 29,338
  • 17
  • 103
  • 134