简体   繁体   English

javascript在执行下一次代码之前等待

[英]javascript wait before executing next time of code

i have this code i'm running in firebug 我有这个代码我在firebug中运行

for(var i = 0; i < 3; i = i+1) 
{
    console.log("hi "+i);
    setTimeout(function()
    {
        console.log("hi again "+i);
    }, 10000); 
}

what i'm trying to do is that in every iteration, it will output the first message, wait 10 seconds then output the second message before going though the next iteration 我想要做的是,在每次迭代中,它将输出第一条消息,等待10秒然后输出第二条消息,然后再进行下一次迭代

when i run it however, the first message it outputted 3 times before the second message it outputted even once, i am wondering how i can fix my code to wait before executing the next line of code, in this case, proceeding with the next iteration 然而,当我运行它时,它输出的第一条消息在它输出的第二条消息之前输出了3次,我想知道如何在执行下一行代码之前修复我的代码等待,在这种情况下,继续进行下一次迭代

The problem here is that the body of the loop runs to completion before any of the callbacks to setTimeout run. 这里的问题是循环体在运行setTimeout任何回调之前运行完成。 Hence it will print all of the "hi" messages before any of the "hi again" ones. 因此,它将在任何“hi again”消息之前打印所有“hi”消息。 In order to fix this you will need to schedule the "hi" messages to run after the "hi again" ones run. 为了解决这个问题,您需要安排“hi”消息在“hi again”运行之后运行。 For example 例如

(function() { 
  var go = function(count) { 
    console.log("hi " + count);
    setTimeout(function() { 
      console.log("hi again " + count);
      if (count < 3) { 
        go(count + 1);
      }, 10000);
  };

  go(0);
})();

When you call setTimeout, it says "keep doing what you are doing, but in X milliseconds do this too. So you need to do something like: 当你调用setTimeout时,它会说“继续做你正在做的事情,但是在X毫秒内也这样做。所以你需要做类似的事情:

function sayHi(i) {
    console.log("hi "+i);
    setTimeout(function()
    {
        console.log("hi again "+i);
        if (i < 3) sayHi(i+1);
    }, 10000);
}

sayHi(0);

You can always write simple time-consuming function to help you with your task 您总是可以编写简单耗时的功能来帮助您完成任务

function pauseScript(seconds) {
  var stop = Date.now() + seconds*1000;
  for (var i; stop >= Date.now(); i++){}
}

and call it when you want to "stop" your code for some time 并且当你想要“停止”代码一段时间时调用它

for (var i=1; i<=10; i++) {
  pauseScript(10) // pause 10 seconds
  var d = new Date();
  console.log("pass #"+i+" [time now = "+d.toTimeString().substr(0,8)+']');
}

in console log you'll see something like this 在控制台日志中你会看到这样的东西 在此输入图像描述

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

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