Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout() with string or (anonymous) function reference? speedwise [closed]

Which one of these two ways is faster and why?

window.setTimeout("func()", 100);

Or

window.setTimeout(function(){func();}, 100);

I'm guessing the second way is faster if for no other reason other than John Resig and all the ninjas use it, I'm guessing because it already parsed as opposed to the first way which it would have to create a new parsing "thingie". I vaguely recall this being one of the reasons people don't like eval().

Also while I have you here, in the second code snipplet, is the first semi-colon considered good practice in such a case?

like image 894
qwertymk Avatar asked Dec 22 '10 04:12

qwertymk


People also ask

What is the use of setTimeout () in JavaScript?

setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.

Does setTimeout block execution?

Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute.

Is setTimeout asynchronous?

One potential caveat to be aware of is the fact that setTimeout is asynchronous. It queues the function reference it receives to run once the current call stack has finished executing.

What is setTimeout in JavaScript?

setTimeout accepts a reference to a function as the first argument. This can be the name of a function: A variable that refers to a function (a function expression): Or an anonymous function:

What is the use of setTimeout in Swift?

Examples of Use. setTimeout accepts a reference to a function as the first argument. This can be the name of a function: function greet(){ alert('Howdy!'); } setTimeout(greet, 2000); A variable that refers to a function (a function expression): const greet = function(){ alert('Howdy!'); }; setTimeout(greet, 2000); Or an anonymous function:

Can you use arrow functions with setTimeout?

You can, of course, use them with setTimeout, but there’s one gotcha to be aware of — namely, that arrow functions don’t have their own this value. Instead, they use the this value of the enclosing lexical context.


1 Answers

There's a third faster/simpler option:

window.setTimeout(func, 100);

...strictly relating to your question, the second is faster, as it's still a reference - not an evaluation, which is always fairly expensive. As for the semicolon, yes it's a good practice to always use them. They should never have been optional in my opinion, but plenty will disagree with me here. You can't really argue against being explicit in your code, that's always a good thing.

like image 54
Nick Craver Avatar answered Nov 16 '22 02:11

Nick Craver