jQuery and setTimeout

后端 未结 4 1528
粉色の甜心
粉色の甜心 2021-01-27 02:37

I have the following code:

            jQuery(document).ready(function()
            {
setTimeout($(\'#loading\').fadeIn(\'slow\'), 9999);
            });
         


        
4条回答
  •  -上瘾入骨i
    2021-01-27 03:02

    In order to do what you want, you have to wrap the jQuery stuff in an anonymous function:

    setTimeout(function () {
        $('#loading').fadeIn('slow');
    }, 9999);
    

    The setTimeout function (and setInterval as well) must be told what to do after the delay. And there are only three ways to tell it what to do:

    1. With a string of JavaScript that it must eval:

      setTimeout('$("#loading").fadeIn("slow")', 9999);
      

      Because this uses eval, and can get pretty ugly, it's not recommended. But it works fine.

    2. With a function reference:

      var test = function () {
          $('#loading').fadeIn('slow');
      };
      
      setTimeout(test, 9999);
      

      Note that I didn't do setTimeout(test(), 9999). I just gave it the name of the function.

    3. With an anonymous function that you construct on the fly, which is what I did in the first code block above.

    If you try to do something like setTimeout(test(), 9999), then the browser will first execute test(), and then give the return value to setTimeout. So in your attempt...

    setTimeout($('#loading').fadeIn('slow'), 9999);
    

    ...the browser was executing that jQuery stuff, fading in the #loading element, and then giving whatever fadeIn returns to setTimeout. As it happens, the fadeIn function returns a jQuery object. But setTimeout doesn't know what to do with objects, so nothing would happen after the 9999 millisecond delay.

提交回复
热议问题