Javascript function call with/without parentheses

后端 未结 6 1771
南旧
南旧 2021-02-11 07:39

code_0:

(calling foo without parentheses)

function foo(){
    console.log(\'hello world\');
}

setTimeout(foo, 2000);

This

6条回答
  •  醉话见心
    2021-02-11 08:03

    In the first code snippet, the function foo is being passed to the timeout. That means that foo gets called after 2 seconds when the timeout expires.

    In the second code snippet, the function foo is being called to decide what to pass to the timeout. So foo gets called before the timeout is set. Since foo() doesn't return anything, nothing happens when the timeout expires.

提交回复
热议问题