jQuery and setTimeout

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

I have the following code:

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


        
相关标签:
4条回答
  • 2021-01-27 02:59

    setTimeout accepts a function as first parameter - you are currently passing a jQuery selector, which immediately gets evaluated which executes the fadeIn operation. Instead pass in an anonymous function:

    setTimeout(function() {
     $('#loading').fadeIn('slow'), 9999);
    }, 9999);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-27 03:05

    You can also use jQuery's .delay().

    $('#loading').delay(9999).fadeIn('slow');

    0 讨论(0)
  • 2021-01-27 03:22

    The settimeout() function is from javascript and takes a function as an argument.

    Best choice would be to use jQuery's builtin delay() function:

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

    More information/exemples: http://api.jquery.com/delay/

    0 讨论(0)
提交回复
热议问题