thandasoru
thandasoru

Reputation: 1558

Javascript function calling within setTimeout - which is better?

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"?

Upvotes: 1

Views: 149

Answers (3)

voithos
voithos

Reputation: 70552

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.

Upvotes: 2

Blender
Blender

Reputation: 298136

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);

Upvotes: 4

ozczecho
ozczecho

Reputation: 8849

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

Upvotes: 3

Related Questions