Javascript 带和不带引号和括号的 setTimeout 之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10312963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:49:13  来源:igfitidea点击:

Difference between setTimeout with and without quotes and parentheses

javascriptsettimeout

提问by user1316123

I am learning JavaScript and I have learned recently about JavaScript timing events. When I learned about setTimeoutat W3Schools, I noticed a strange figure which I didn't run into before. They are using double quotes and then call the function.

我正在学习 JavaScript,最近我了解了 JavaScript 计时事件。当我setTimeoutW3Schools学习时,我注意到一个我以前没有遇到过的奇怪人物。他们使用双引号然后调用函数。

Example:

例子:

setTimeout("alertMsg()", 3000);

I know that double and single quotes in JavaScript means a string.

我知道 JavaScript 中的双引号和单引号表示字符串。

Also I saw that I can do the same like that:

我也看到我可以这样做:

setTimeout(alertMsg, 3000);

With the parentheses it's referring, without the parentheses it's copied. When I am using the quotes and the parentheses it's getting crazy.

带括号的是引用,不带括号的是复制。当我使用引号和括号时,它变得很疯狂。

I will be glad if someone can explain to me the difference between these three ways of using setTimeout:

如果有人能向我解释这三种使用方式之间的区别,我会很高兴setTimeout

With the parentheses:

带括号:

setTimeout("alertMsg()", 3000);

Without the quotes and the parentheses:

没有引号和括号:

setTimeout(alertMsg, 3000);

And the third is only using quotes:

第三个是只使用引号:

setTimeout("alertMsg", 3000);


N.B.: A better source for setTimeoutreference would be MDN.

注意:更好的setTimeout参考来源是MDN

回答by Joseph

Using setIntervalor setTimeout

使用setIntervalsetTimeout

You should pass a reference to a function as the first argument for setTimeoutor setInterval. This reference may be in the form of:

您应该传递对函数的引用作为setTimeoutor的第一个参数setInterval。该参考可以采用以下形式:

  • An anonymous function

    setTimeout(function(){/* Look mah! No name! */},2000);
    
  • A name of an existing function

    function foo(){...}
    
    setTimeout(foo, 2000);
    
  • A variable that points to an existing function

    var foo = function(){...};
    
    setTimeout(foo, 2000);
    

    Do note that I set "variable in a function" separately from "function name". It's not apparent that variables and function names occupy the same namespace and can clobber each other.

  • 匿名函数

    setTimeout(function(){/* Look mah! No name! */},2000);
    
  • 现有函数的名称

    function foo(){...}
    
    setTimeout(foo, 2000);
    
  • 指向现有函数的变量

    var foo = function(){...};
    
    setTimeout(foo, 2000);
    

    请注意,我将“函数中的变量”与“函数名称”分开设置。变量和函数名称占据相同的命名空间并且可以相互破坏并不明显。

Passing arguments

传递参数

To call a function and pass parameters, you can call the function inside the callback assigned to the timer:

要调用函数并传递参数,您可以在分配给计时器的回调中调用该函数:

setTimeout(function(){
  foo(arg1, arg2, ...argN);
}, 1000);

There is another method to pass in arguments into the handler, however it's not cross-browser compatible.

还有另一种方法可以将参数传递给处理程序,但它不是跨浏览器兼容的

setTimeout(foo, 2000, arg1, arg2, ...argN);

Callback context

回调上下文

By default, the context of the callback (the value of thisinside the function called by the timer) when executed is the global object window. Should you want to change it, use bind.

默认情况下,回调的上下文(this定时器调用的函数内部的值)在执行时是全局对象window。如果您想更改它,请使用bind.

setTimeout(function(){
  this === YOUR_CONTEXT; // true
}.bind(YOUR_CONTEXT), 2000);

Security

安全

Although it's possible, you should not pass a stringto setTimeoutor setInterval. Passing a string makes setTimeout()or setInterval()use a functionality similar to eval()that executes strings as scripts, making arbitrary and potentially harmful script execution possible.

尽管这是可能的,但您不应将字符串传递setTimeoutsetInterval。将字符串传递使setTimeout()setInterval()使用类似的功能eval()执行字符串作为脚本,使得任意的和潜在的有害脚本执行可能的。

回答by Acil Az

i think the setTimeout function that you write is not being run. if you use jquery, you can make it run correctly by doing this :

我认为您编写的 setTimeout 函数没有运行。如果您使用 jquery,您可以通过执行以下操作使其正确运行:

    function alertMsg() {
      //your func
    }

    $(document).ready(function() {
       setTimeout(alertMsg,3000); 
       // the function you called by setTimeout must not be a string.
    });

回答by Nicocube

Totally agree with Joseph.

完全同意约瑟夫。

Here is a fiddle to test this: http://jsfiddle.net/nicocube/63s2s/

这是一个测试这个的小提琴:http: //jsfiddle.net/nicocube/63s2s/

In the context of the fiddle, the string argument do not work, in my opinion because the function is not defined in the global scope.

在小提琴的上下文中,字符串参数不起作用,在我看来,因为该函数未在全局范围内定义。

回答by Vitaliy Markitanov

What happens in reality in case you pass string as a first parameter of function

如果您将字符串作为函数的第一个参数传递,实际上会发生什么

setTimeout('string',number)

设置超时( 'string', number)

is value of first param got evaluated when it is time to run (after numberof miliseconds passed). Basically it is equal to

是在运行时(经过number几毫秒后)评估的第一个参数的值。基本上它等于

setTimeout(eval('string'), number)

设置超时( eval('string'), number)

This is

这是

an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.

允许您包含字符串而不是函数的替代语法,该函数在计时器到期时被编译和执行。不推荐使用此语法的原因与使用 eval() 存在安全风险的原因相同。

So samples which you refer are not good samples, and may be given in different context or just simple typo.

因此,您引用的样本不是好的样本,可能会在不同的上下文中给出,或者只是简单的错字。

If you invoke like this setTimeout(something, number), first parameter is not string, but pointer to a something called something. And again if somethingis string - then it will be evaluated. But if it is function, then function will be executed. jsbin sample

如果您这样调用setTimeout(something, number),第一个参数不是字符串,而是指向名为something. 再次如果something是字符串 - 那么它将被评估。但是如果是函数,那么函数就会被执行。 jsbin 示例

回答by Avinash Khadsan

    ##If i want to wait for some response from server or any action we use setTimeOut.

    functionOne =function(){
    console.info("First");

    setTimeout(()=>{
    console.info("After timeOut 1");
    },5000);
    console.info("only setTimeOut() inside code waiting..");
    }

    functionTwo =function(){
    console.info("second");
    }
    functionOne();
    functionTwo();

## So here console.info("After timeOut 1"); will be executed after time elapsed.
Output:
******************************************************************************* 
First
only setTimeOut() inside code waiting..
second
undefined
After timeOut 1  // executed after time elapsed.

回答by Srikrushna

With the parentheses:

带括号:

setTimeout("alertMsg()", 3000); // It work, here it treat as a function

Without the quotes and the parentheses:

没有引号和括号:

setTimeout(alertMsg, 3000); // It also work, here it treat as a function

And the third is only using quotes:

第三个是只使用引号:

setTimeout("alertMsg", 3000); // It not work, here it treat as a string

function alertMsg1() {
        alert("message 1");
    }
    function alertMsg2() {
        alert("message 2");
    }
    function alertMsg3() {
        alert("message 3");
    }
    function alertMsg4() {
        alert("message 4");
    }

    // this work after 2 second
    setTimeout(alertMsg1, 2000);

    // This work immediately
    setTimeout(alertMsg2(), 4000);

    // this fail
    setTimeout('alertMsg3', 6000);

    // this work after 8second
    setTimeout('alertMsg4()', 8000);

In the above example first alertMsg2() function call immediately (we give the time out 4S but it don't bother) after that alertMsg1() (A time wait of 2 Second) then alertMsg4() (A time wait of 8 Second) but the alertMsg3() is not working because we place it within the quotes without parties so it is treated as a string.

在上面的例子中,第一个 alertMsg2() 函数立即调用(我们给出了 4S 的超时时间,但它不会打扰),然后 alertMsg1()(等待 2 秒)然后 alertMsg4()(等待 8 秒)但是 alertMsg3() 不起作用,因为我们将它放在引号中而没有参与方,因此它被视为字符串。