开发者

jQuery - building a banner with a timeout

I want to build a banner that says "Loading", and hides when the application is done.

<div id="ajaxBanner"></div>


function ajaxBanner(action, confirmMsg) {

    if (action == 'show') {
        $('#msg').text('Loading...');
        $('#ajaxBanner').show();
    } else if (action == 'hide') {
        $('#ajaxBanner').fadeOut();
    } else if (confirmMsg == true) {
        $('#ajaxBanner').show();
        ajaxBanner_timeout = setTimeout(ajaxBanner('hide'), 2000);
    }
};

The function shows a "Loading" banner message to the user and later hides it. The thing is, I also want to use this space for confirmation m开发者_运维问答essages, like "XXXX Added to XXX".

The problem is, when confirmMsg is true, it is getting killed by a subsequent AJAX call with does Action show.

How can I say only do action==show or action==hide when the ajaxBanner_timeout is complete?


One problem is setTimeout() does not take a function call it takes a string or an anonymous function try setTimeout("ajaxBanner('hide')", 2000);. Right now the function is immediately called no pause. Another method is

setTimeout(function(){
  //do something;
},2000);

Note this is the better way.


The problem is you are calling ajaxBanner('hide') in your setTimeout instead of passing in the function reference. Wrapping your ajaxBanner('hide') in an anonymous function will solve the problem:

 setTimeout(function() { ajaxBanner('hide'); }, 2000);

Explanation/Test you can do in your JavaScript Console:

One way to see the difference is to paste this in your Firebug console and run it:

Good:

 // alert fires in 5 seconds
 setTimeout(function() { alert('hide'); }, 5000);

Bad:

 // alert fires right away, despite the 5 second delay
 setTimeout(alert('hide'), 5000);

UPDATE: Note that I am not assigning the setTimeout event to a variable as it's not needed in the above code example in the question.


var ajaxBanner_callback = function (){};
function ajaxBanner(action, confirmMsg) {

  if (action == 'show') {
      var ajaxBanner_callback = function () {
        $('#msg').text('Loading...');
        $('#ajaxBanner').show();
      }
     if (!ajaxBanner_timeout) ajaxBanner_callback();
  }
  else if (action == 'hide') {
      var ajaxBanner_callback = function () {
        $('#ajaxBanner').fadeOut();
      }
     if (!ajaxBanner_timeout) ajaxBanner_callback();
  }
  else if (confirmMsg == true) {
      $('#ajaxBanner').show();
      ajaxBanner_timeout = setTimeout(function () {
        ajaxBanner_callback();
        clearTimeout(ajaxBanner_timeout);
        ajaxBanner_callback = function (){};
      }, 2000);
  }
};

You can do the same to the confirmMsg if you want.

It might be useful investigating into $.queue()

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜