Why does calling setTimeout with parenthesis not s

2019-01-15 10:47发布

The following code has a new callstack when the debugger fires in d (jsfiddle here)

function c() {
    setTimeout( d, 1000 );
}

function d() {
    debugger;   
}

c();

If we modify the code to use setTimeout( d(), 1000 ); which has brackets (parenthesis:)

function c() {
    setTimeout( d(), 1000 );
}

function d() {
    debugger;   
}

c();

then the callstack has both c() and d() (jsfiddle here). Why?

3条回答
Evening l夕情丶
2楼-- · 2019-01-15 11:12

Because in the first example you are passing a function pointer as the thing to execute in 1 second. In the second example you have already executed d, and you are passing the results of d() to setTimeout to call in 1 second.

查看更多
时光不老,我们不散
3楼-- · 2019-01-15 11:28

You are not passing setTimeout the function d in the second example; you are instead passing d(), which is the result of calling d.

The result of calling d is undefined since it returns nothing, which converts to the string "undefined", which is then evaled, doing... precisely nothing.


With regard to callstacks, since you are calling d inside of c, that is why you see c in the callstack. To clarify, your second example is the same as

function c() {
    var temp = d();
    setTimeout(temp, 1000);
}

function d() {
    debugger;   
}

c();
查看更多
4楼-- · 2019-01-15 11:29

SetTimeout takes a function argument. If you pass a string, it acts like eval. If you invoke the function, like you did, it fires immediately then setTimeout fires with the results in a new call stack.

查看更多
登录 后发表回答