Javascript setTimeout等待setTimeout

Javascript setTimeout等待setTimeout,javascript,jquery,Javascript,Jquery,我偶然发现了一个问题: 代码应该按该顺序输出“hi1”、“hi2”、“hi3”和“hi4”。 我写了这个简化的代码,实际的代码更复杂,导致我无法删除我标记的一些函数 function test() { console.log("hi2"); setTimeout(function () { //maybe replace this? console.log("hi3"); }, 2000); } console.log("hi1"); test(); setTi

我偶然发现了一个问题: 代码应该按该顺序输出“hi1”、“hi2”、“hi3”和“hi4”。 我写了这个简化的代码,实际的代码更复杂,导致我无法删除我标记的一些函数

function test() {
    console.log("hi2");
    setTimeout(function () { //maybe replace this?
    console.log("hi3");
    }, 2000);
}

console.log("hi1");
test();
setTimeout(function () { //cannot get rid of this
    console.log("hi4");
}, 0);

如何使其按顺序输出?

如果需要等待
test()中的
setTimeout
执行后才能继续,最简单的方法是使用回调:

function test(callback) {
    console.log("hi2");
    setTimeout(function () {
        console.log("hi3");
        // Execute additional logics
        callback();
    }, 2000);
}

console.log("hi1");
test(function () {
    setTimeout(function () {
        console.log("hi4");
    }, 0);
});

使用回调或尝试显示您的复杂代码更复杂。我们可以帮助您分析它。

正如其他人指出的,setTimeout是异步的,因此它们在后台运行,而其余的代码则继续运行。我猜现在你会得到这样的结果:

hi1
hi2
hi4
then a 2000ms delay, then
hi3
function showMessage(msg, delay) {
    setTimeout(function() {
        console.log(msg);
    }, delay);
}
showMessage('hi1', 0);
showMessage('hi2', 2000);
showMessage('hi3', 4000);
showMessage('hi4', 6000);
如果代码更改不多,请尝试将hi4的延迟更改为4000,如:

setTimeout(function () { //cannot get rid of this
    console.log("hi4");
}, 4000);
这应该可以解决订单问题,但仍然相当混乱和不可靠。我想要一些像:

hi1
hi2
hi4
then a 2000ms delay, then
hi3
function showMessage(msg, delay) {
    setTimeout(function() {
        console.log(msg);
    }, delay);
}
showMessage('hi1', 0);
showMessage('hi2', 2000);
showMessage('hi3', 4000);
showMessage('hi4', 6000);

为什么要标记
jQuery
setTimeout
是异步的,您编写语句的顺序不是它们执行的顺序。如果您想等待某件事情完成,您必须使用回调或承诺(一种链接回调的好方法)。
setTimeout(function(){//无法消除此问题
为什么???您应该解释它