简体   繁体   English

Javascript - 关于设置超时的问题

[英]Javascript - Question regarding Set Timeout

As per my understanding, the below function should print 5 five times because of hoisting .据我了解,下面的 function 应该打印5 5 次,因为吊装 But instead, it prints 6 five times .但相反,它打印了6 五次

Question is, how come it prints 6 when the loop's limit is <=5 ?问题是,当循环的限制为<=5时,它怎么会打印6

function () {
  for ( var i = 1; i <= 5; i++) {
    setTimeout( function() {
      console.log(i); // 👈 this should print '5' five times 
    }, i * 1000)
  }
}

It prints 6 because that's the value of i when the loop exits.它打印 6 因为这是循环退出时i的值。

Consider the flow at the end of the loop's run, when i is 4:考虑循环运行结束时的流程,当i为 4 时:

  • Is i <= 5?我 <= 5 吗? Yes.是的。
  • execute the body执行身体
  • increment i to 5将 i 增加到 5
  • Is i <= 5?我 <= 5 吗? Yes.是的。
  • execute the body执行身体
  • increment i to 6将 i 增加到 6
  • Is i <= 5?我 <= 5 吗? No.不。
  • exit the loop退出循环

The for loop stops after the i++ occurs which meets the condition for exiting (ie 6 > 5 ) - at that point, the value of i has incremented to 6 already and about a second later the value of i is printed在满足退出条件的i++发生后 for 循环停止(即6 > 5 ) - 此时, i的值已经增加到6并且大约一秒钟后i的值被打印

It is because of the increment you apply sol =>这是因为您应用的增量 sol =>

function num() {
  for ( var i = 1; i <= 4; i++) {
    setTimeout( function() {
      console.log(i); // 👈 this should print '5' five times 
    }, i * 1000)
  }
}
num()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM