Which of these constructs is better and why
setTimeout(function() { $('#secret').hide(); }, 5000);
setTimeout( "$('#secret').hide();", 5000);
$('#secret').show(5000, function(){ this.hide(xxx)} );
Which of these constructs is better and why
setTimeout(function() { $('#secret').hide(); }, 5000);
setTimeout( "$('#secret').hide();", 5000);
$('#secret').show(5000, function(){ this.hide(xxx)} );
Because you are using jQuery I think you should use third one.
Without jQuery first is better than second, because in second case JS engine has to eval expression and in first one doesn't.
The first one for sure, it uses an anonymous function to capture the function to execute after the timeout.
Second one uses eval()
to evaluate your string, which would probably be slower than the first option (nevermind the arguments for why using eval()
is bad).
Third one shows the element over 5 seconds and then hides as soon as it completes, therefore is different from the first.
UPDATE:
nickf's update prompted me to look through the source and number 3 will execute immediately if the element is already visible. Here are the relevant lines of source code
if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
return opt.complete.call(this);
With the first one you loose the ability of concatenate that function with others. The second one is an evaluated string so you must be carefull about the context and anywway it's not good for performace. The last is better because after that you can call other jquery methods and jquery has also a better time-management.
The first example and the third function differently, the first 5 seconds hidden '# secret' and the third is doing slowly in 5 seconds. it all depends on what you want to do.
Between options one and two, option one is better, since it doesn't need to evaluate the string to convert it to executable code.
Option three doesn't do the same thing. It might have the same output, but only because of a kludge: using some other function which takes a long time before calling the one you want. It's very inefficient and doesn't show exactly what you're trying to do.
Go with option one.
edit: Actually, I've just tested your option three, and can say that if the element is visible, then the callback happens immediately, regardless of the timeout you pass to the show()
function.