使用 setTimeout() 时调用堆栈

She*_*shi 2 javascript

我对 setTimeout 有点困惑。我想确认以下代码的输出是否始终是:

inside abc
inside sample
Run Code Online (Sandbox Code Playgroud)

代码:

function abc() {
    xyz();

    // interactions and modifications in DOM 
    $("#id1").append("something");
    $("#id2").val("set something");
    $("#id3").after("create some dynamic element");
    // 10 to 20 interaction more...

    console.log('inside abc');
}

function xyz() {
    setTimeout(function() {
        sample();
    },0);  
}

function sample() {
    console.log('inside sample')
}
Run Code Online (Sandbox Code Playgroud)

如果有人可以用调用堆栈解释整个流程,那就太好了。

JLR*_*she 7

是的,它总是会有这样的输出。

在执行上下文清除之前,a 内的回调setTimeout不会被调用 - 即当前执行的代码序列已完成。

这意味着即使你这样做

setTimeout(function () { console.log("1 second!"); }, 1000);

var start = +new Date();
while ((+new Date()) - start < 5000) {}
Run Code Online (Sandbox Code Playgroud)

1 second!超过 5 秒后不会被记录。