Which of these setTimeout format is better?

Which of these designs is better and why

setTimeout(function() { $('#secret').hide(); }, 5000); setTimeout( "$('#secret').hide();", 5000); $('#secret').show(5000, function(){ this.hide(xxx)} ); 
+4
source share
5 answers

The first, of course, uses an anonymous function to capture a function executed after a timeout.

The second uses eval() to evaluate your string, which is likely to be slower than the first option (do not read the arguments why using eval() is bad).

The third shows the element for 5 seconds and then hides as soon as it is completed, therefore it differs from the first.

UPDATE:

Update

nickf prompted me to look at the source, and number 3 will execute immediately if the item 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); 
+4
source

Between options one and two, option one is better, since it does not need to evaluate the string in order to convert it to executable code.

Option three does not do the same. It may have the same result, but only because of kludge: using some other function that takes a long time before calling the one you want. This is very inefficient and does not show exactly what you are trying to do.

Go with the first option.

edit: Actually, I just checked your option three and can say that if the element is visible, then the callback happens immediately, regardless of the timeout that you pass to the show() function.

+2
source

With the first, you lose the ability to concatenate this function with others. The second is the evaluation line, so you have to be careful about the context, and still this is not good for performace. The latter is better, because after that you can call other jquery methods, and jquery also improves time management.

0
source

The first example and the third function are different, the first 5 seconds the hidden "# secret" and the third do slowly after 5 seconds. it all depends on what you want to do.

0
source

Since you are using jQuery, I think you should use a third.
Without jQuery, the first is better than the second, because in the second case, the JS engine should parse the expression, and in the first, no.

-3
source

All Articles