jQuery fadeIn after setTimeout

I want to fade in an element after a set amount of time. I’ve been messing with this snippet but I’m certain my logic/syntax is wrong.


$(function(){
	window.setTimeout('fadeImage()', 9000);
	
	function fadeImage(){
		$('#tag').fadeIn(4000);	
	}
});

Firstly you shouldn’t be feeding a string as this gets eval()'d and is slower than a reference, so update the setTimeout to be:

window.setTimeout( fadeImage, 9000 );

And, is #tag hidden initially? Got a page link?

You fixed it, thanks again. I suppose window.setTimeout(‘fadeImage()’, 9000); was not working because fadeImage wasn’t returning anything? and it should have been a reference like you said?

(i looked at many setTimeout examples before posting here and they all had the parentheses.)

Since fadeImage without quotes is a reference, and referring to it in the same exact script block is no problem, I think the only explanation is that eval() requires the function to be defined beforehand, you could test this by moving the function definition and trying it the other way, and if it works then that is the explanation.

Moving the function anywhere inside of the anonymous function won’t do any good. It would need to be moved to a completely outside scope, at which point the function becomes a direct child of the window object itself.

When the string is evaluated at the time when the timeout point is reached, the function itself is not available because it’s effectively hidden inside of anonymous function.

When no strings are used and you reference the name of the function, that works because when the anonymous function is entered, all functions inside it exist, and the reference is able to be made while you’re inside the anonymous function itself.

That is my understanding of things anyway.

Oh I see what you’re saying, because setTimeout is a method of window and there are no references, no use of closures is being used since you’re feeding a string so the only way it would reference it would be is if it was in the global namespace or the same namespace as the caller object ( window ) … learn something new everyday.

I guess I started out with best practices since I never relied on this and always used references ( less to type too ) - feel free to correct me if my understanding was off.

Nope, no correction necessary - I think you’ve got it now.