简体   繁体   English

在setTimeout中调用Javascript函数-哪个更好?

[英]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: 版本1:

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

Version 2: 版本2:

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

One more doubt, is the Version 2 way of calling called "Closure"? 另一个疑问是,版本2的调用方式称为“关闭”吗?

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: 我更喜欢#2 ,因为它更干净并且使语法可读:

setTimeout(function() {
  showMsg('hi');
}, 1000);

Yes , version 2 is called Closure. 是的,版本2称为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. 正如@Blender所说,我也更喜欢2 ,因为它不会使用(半没用的)“调用程序”函数污染全局空间。 It's clean, and it simple to understand to someone who knows how setTimeout works. 它很干净,对于知道setTimeout工作原理的人来说很容易理解。 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. 在JavaScript中,就像在许多其他动态语言中一样,函数是一等公民 ,这意味着它们可以创建和传递-它们是对象。 However, a closure is more than just an anonymous function. 但是,闭包不仅仅是匿名函数。 The answers to this question explain what a closure is quite succinctly. 这个问题的答案解释了闭包是多么简洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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