1

I have the following code:

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

which should slowly fade in the loading element after 9999 miliseconds but instead it fades it in straight away... why?

Can anyone help. Thanks

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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/

Comments

3

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);

1 Comment

Small error on the grammar, you should edit to make your answer clearer to non-js-addicts eyes who corrected this on their own =) Otherwise, Good answer.
1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.