简体   繁体   中英

javascript wait before executing next time of code

i have this code i'm running in 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

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

The problem here is that the body of the loop runs to completion before any of the callbacks to setTimeout run. Hence it will print all of the "hi" messages before any of the "hi again" ones. In order to fix this you will need to schedule the "hi" messages to run after the "hi again" ones run. 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:

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 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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