简体   繁体   中英

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM