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
In order to do what you want, you have to wrap the jQuery stuff in an anonymous function:
The
setTimeoutfunction (andsetIntervalas well) must be told what to do after the delay. And there are only three ways to tell it what to do:With a string of JavaScript that it must
eval:Because this uses
eval, and can get pretty ugly, it’s not recommended. But it works fine.With a function reference:
Note that I didn’t do
setTimeout(test(), 9999). I just gave it the name of the function.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 executetest(), and then give the return value tosetTimeout. So in your attempt……the browser was executing that jQuery stuff, fading in the
#loadingelement, and then giving whateverfadeInreturns tosetTimeout. As it happens, thefadeInfunction returns a jQuery object. But setTimeout doesn’t know what to do with objects, so nothing would happen after the 9999 millisecond delay.