2

I am AJAXing in content from external pages. Most of the time the load takes less than a second, but is there a way I can fade in a div (lets say a preload div) which comes up if say the load takes longer than 3 seconds? So something like this...

$targetPoint.load($dataImportURL + " " +$rawCollectionPoint,function(){
    if (($(this).load >= 3))
    {
        alert ("Its taken more than 3 seconds to load");
    }                       
});
Andrew Junior Howard
  • 2,427
  • 4
  • 29
  • 45
  • Search ajax + timeout :) Here you go : http://stackoverflow.com/questions/3543683/jquery-ajax-timeout-setting – TimTastic Sep 18 '12 at 20:38
  • 1
    I don't think he wants to kill the request. I think he wants to notify the user that the request is taking longer than it should. – BZink Sep 18 '12 at 20:40
  • Oh, my bad. Then ignore my link! :) – TimTastic Sep 18 '12 at 20:42
  • Your absolutely right BZink. I just want to fade in a preload screen of some description if its taking too long rather than making the user waiting around wondering whats going on lol – Andrew Junior Howard Sep 18 '12 at 20:49

1 Answers1

6

Take a look at the JavaScript setTimeout function.

When you send off your ajax call...

var timeout = setTimeout(function(){
    alert ("Its taken more than 3 seconds to load");
}, 3000);

And when the ajax call completes cancel the timeout trigger.

clearTimeout(timeout);

Edit: you may have to use the .ajax() function from jQuery so you can take advantage of the beforeSend and success callbacks

Something like this...

var timeout;
$.ajax({
   url: $dataImportURL + " " +$rawCollectionPoint
   beforeSend: function(){
       timeout = setTimeout(function(){
        alert ("Its taken more than 3 seconds to load");
    }, 3000);
   }
   success: function(data){
       clearTimeout(timeout);
       $targetPoint.html(data);
   }

});
BZink
  • 7,387
  • 10
  • 36
  • 55