1

I have two versions of the code. Can someone let me know which is optimal and faster?

Version 1:

function showMsg(a)
{
    alert(a);
}
function invokeShowMsg()
{
    var msg = 'hi';
    showMsg(msg);
}
window.setTimeout(invokeShowMsg,1000);

Version 2:

function showMsg(a)
{
    alert(a);
}
window.setTimeout(function(){showMsg('hi');},1000);

One more doubt, is the Version 2 way of calling called "Closure"?

3
  • What are your criteria for "optimal"? I suspect #1 is faster because it passes a reference to an already declared function rather than evaluating a function expression and passing a reference to that—but you should test it in various browsers. In any case, if execution is delayed by a minimum of 1 second, of what relevance is speed? Commented Jan 23, 2012 at 4:44
  • Since I run it in a Mobile browser, will version 2 cause any adverse impact? Commented Jan 23, 2012 at 4:51
  • You will not notice it, even if you tried. Most* JS engines compile the code. Commented Jan 23, 2012 at 4:56

3 Answers 3

4

As far as speed goes, you will not notice any difference between the two whatsoever, so pick what you like.

I prefer #2, as it is cleaner and keeps the syntax readable:

setTimeout(function() {
  showMsg('hi');
}, 1000);
Sign up to request clarification or add additional context in comments.

3 Comments

I just say yes because it makes no difference whatsoever to me, as I haven't really found a practical use for distinguishing an anonymous function and a closure (even if I use both).
But +1 for actually knowing the answer. I retract my statement in shame.
3

Yes , version 2 is called Closure. As far as speed, they are both equivalent.

1 Comment

Thanks, I read somewhere in Google's pages where it said version 2 (closure) is slower than version 1. I used version 2 all over my code and I don't really want to change it now..
2

As @Blender said, I also prefer 2, as it doesn't pollute the global space with (semi-useless) "caller" functions. It's clean, and it simple to understand to someone who knows how setTimeout works. And as far as speed goes, there's virtually no difference. Here's a performance comparison of the two methods.

However, as far as I understand, it is not a closure. It is simply an anonymous function. In JavaScript, as in many other dynamic language, functions are first class citizens, meaning that they can be created and passed around- they are objects. However, a closure is more than just an anonymous function. The answers to this question explain what a closure is quite succinctly.

1 Comment

thanks for the link.. excellent description provided there :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.