setTimeout在控制台上的随机行为.如何获得计数的顺序和这种行为的原因? [英] Random behavior of setTimeout on console. How to get counts in order and reason for this behavior?

查看:79
本文介绍了setTimeout在控制台上的随机行为.如何获得计数的顺序和这种行为的原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for (var i = 0; i < 5; i++) {
  function timer(j) {
    setTimeout(function() {
      alert(j);
    }, 1000);
  }
  timer(i);
};

此代码正在生成计数的随机结果.为什么会出现这种情况,我该怎么做才能获得正确的有序计数.

This code is generating random outcomes of count. Why is this behavior and what can I do to get proper ordered counts.

推荐答案

脚本运行时,for循环正在运行,并且您一次初始化5个setTimeout,每个在1000次后超时毫秒.因为它们都设置为同时运行,并且由于setTimeout甚至不精确到毫秒,所以超时顺序将不可预测.另一个潜在的混淆因素是alert 阻止.

When the script runs, the for loop is running, and you are initializing 5 setTimeouts all at once, each of which times out after 1000 milliseconds. Because they're all set to run at the same time, and since setTimeout isn't even millisecond-precise, the timeout order won't be predictable. Another potential confounding factor is that alert blocks.

如下注释所示,setTimeout可能可以按设置的顺序运行,但不能保证-行为可能因浏览器而异.因此,如果要确保它们按照设置的顺序运行,请为每次迭代添加几毫秒:

As the comments below illustrate, the setTimeouts may happen to run in the order they were set, but it's not guaranteed - behavior may differ across browsers. So, if you want to make sure they run in the order they were set, add a few milliseconds for each iteration:

for (var i = 0; i < 5; i++) {
  function timer(j) {
    setTimeout(function() {
      console.log(j);
    }, 1000 + (j * 12));
  }
  timer(i);
}

alert版本:

for (var i = 0; i < 5; i++) {
  function timer(j) {
    setTimeout(function() {
      alert(j);
    }, 1000 + (j * 12));
  }
  timer(i);
}

这篇关于setTimeout在控制台上的随机行为.如何获得计数的顺序和这种行为的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆