我偶然发现了一个问题:代码应该按该顺序输出"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);如何使其按顺序输出?
发布于 2014-01-12 19:42:29
如果您需要等待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);
});发布于 2014-01-12 19:59:22
使用回调或尝试显示您的复杂代码更多。我们可以帮你分析一下。
发布于 2014-01-12 20:01:43
正如其他人所指出的那样,setTimeout是异步的,所以它们在后台运行,而其余的代码继续运行。我猜现在你会得到类似这样的东西:
hi1
hi2
hi4
then a 2000ms delay, then
hi3如果你不能更改太多代码,那么尝试将hi4的延迟更改为4000,如下所示:
setTimeout(function () { //cannot get rid of this
console.log("hi4");
}, 4000);这应该可以修复顺序,但它仍然相当混乱和不可靠。我更喜欢这样的:
function showMessage(msg, delay) {
setTimeout(function() {
console.log(msg);
}, delay);
}
showMessage('hi1', 0);
showMessage('hi2', 2000);
showMessage('hi3', 4000);
showMessage('hi4', 6000);https://stackoverflow.com/questions/21074129
复制相似问题