Why does calling setTimeout with parenthesis not s

2019-01-15 10:34发布

问题:

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?

回答1:

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


回答2:

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.



回答3:

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.