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 Howard
  • 2,818
  • 5
  • 33
  • 59
  • 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 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,687
  • 10
  • 37
  • 55
  • But that will just run the function as soon as the load function has completed. I need something which checks up on the load progress. – Andrew Howard Sep 18 '12 at 20:39
  • Ah just got your edit now :) that looks good I'll give this a try. Many thanks for your help :D – Andrew Howard Sep 18 '12 at 20:41
  • No it didn't work unfortunately :( Its missing some commas somewhere I think. I put them in place (correctly I think) but it still didn't work. – Andrew Howard Sep 28 '12 at 15:04
  • I didn't expect that you'd just copy/paste the code, so I'm sure there are some typos. I see the missing commas. Are you getting any javascript errors – BZink Sep 28 '12 at 17:06