同步执行和setTimeout()

时间:2018-05-15 22:29:10

标签: javascript

我的目标是获得以下输出:

1,2(等待2s )3,4(等待2s )5但是我得到1,2,4(等待2s)3,5。 / p>

有谁知道如何解决这个问题?

console.log("1");
console.log("2");
setTimeout(function(){console.log("3")}, 2000);
console.log("4");
setTimeout(function(){console.log("5")}, 2000);

5 个答案:

答案 0 :(得分:1)

因为setTimeout是异步的。 JS转到第一行,打印1,然后打印第二行,打印2,然后打印第三行 - 它是异步,所以它将在稍后执行(在放置时为2000ms),然后在第四行,打印4和第五行,在2000ms执行(作为第三行)。因此,您可以立即获得1,2和4,然后在3和5之后获得2000毫秒。要获得所需内容,请参阅以下代码:



console.log("1")
console.log("2")

setTimeout(function() {
  console.log("3")
  console.log("4")
}, 2000)

setTimeout(function() {
  console.log("5")
}, 4000)




答案 1 :(得分:1)

以下是使用-keep class kotlin.reflect.jvm.internal.** { *; } -dontwarn kotlin.reflect.jvm.internal.** ..

的简单示例

async / await

答案 2 :(得分:1)

您需要了解how JavaScript runs the code

当您调用代码时,它会运行完成,这意味着代码会立即执行。设置超时的作用是将内部函数推送到事件循环以便稍后执行。让我评论一下发生了什么,请记住堆栈的执行模型是先进先出。执行return时,函数将从堆栈中弹出:

// a log function is pushed to stack and popped
console.log("1");

// another log function is pushed to stack and popped
console.log("2");

// setTimeout is pushed to stack and popped
// When popped it added an anonymous function to the event loop
setTimeout(function(){console.log("3")}, 2000);

// another log function is pushed to stack
console.log("4");

// settimeout is pushed to stack and popped

// When popped it added an anonymous function to the event loop
setTimeout(function(){console.log("5")}, 2000);

当没有更多功能可以继续堆叠时,JavaScript引擎开始执行事件循环。因此setTimeous的内部函数等待被推入堆栈。当超时时,它们将被推到堆叠状态。

因此您需要更改代码,如下所示:

// a log function is pushed to stack and popped
console.log("1");

// another log function is pushed to stack and popped
console.log("2");

// first settimeout is pushed to stack
// When executed inner function will be added to event loop because of setTimeout
// In 2000 miliseconds, the event loop will push this function to the stack
setTimeout(function(){
  // When executed
  // another log function will be pushed to stack and popped
  console.log("3")
  
  // another log function will be pushed to stack and popped
  console.log("4");
  
  // second setTimeout is pushed to stack, which in turn pushes inner anonymous function to event loop
  setTimeout(function(){

    // another log function will be pushed to stack and popped
    console.log("5");
      
    // After this point second setTimeout and first setTimeout will be popped in order
      
  }, 2000);
  
}, 2000);

答案 3 :(得分:0)



console.log("1");
console.log("2");
setTimeout(function(){
  console.log("3");
  console.log("4");
  }, 2000);
setTimeout(function(){console.log("5")}, 4000);




答案 4 :(得分:0)