开发者

Ajax loader image: How to set a minimum duration during which the loader is shown?

I am using Jquery for Ajax functionality, and using a loader icon to indicate to the user that data is being retrieved. However, I want the user to see the loader icon for at least 1s, even if the data takes less than 1s to retrieve (if more than 1s is required, the loader icon should remain for the entire duration.

Here is the code for the loader HTML

<img id="loader" s开发者_运维技巧rc="example.com/images/ loader.gif" style="vertical-align: middle; display: none" />

I am using the Jquery .Ajax function for my data processing.


I would use a counter that starts at 2 and is decremented after 1 second and when the ajax response comes in. Something along these lines:

var counter = 2;
function decrement() {
  if (--counter == 0) {
    $('#loader').hide();
  }
}
setTimeout(decrement, 1000);
$.ajax(..., complete: decrement);


First, show the loader image. Then use setTimeout() to to start a timer. When the timer is finished, check if the AJAX has finished, if it has then kill the loader image but if it hasn't then do nothing to the loader image and set a flag. When the AJAX success handler is called, check the flag; if the flag is set then the timer has finished and the success handler can delete the loader image; if the flag is not set, then the success handler can let the timer kill the loader image.

Essentially, you have two asynchronous tasks running (the timeout and the AJAX). The last one to finish kills the loader image.


Here you go. See it in action at http://jsfiddle.net/B4Cge/

var loader = '<img id="loader" src="http://tools.patentcalls.com/images/spinner.gif"/>';

    $(loader).appendTo('#container').load(function() {
        $('#container').find('#loader').delay(3000).fadeOut(function() {
            $('#container').append('your ajax content')
        })
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜