等待执行直到函数调用结束

时间:2017-05-03 09:48:48

标签: javascript settimeout

调用timeout()时,需要100 * 100 ms才能完成。 (成功。不需要修复。)

当调用doThousandTimes()时,它应该花费1000 * 100 * 100 ms来完成。但是,在上一个调用完成之前调用timeout()。我很慢并且一直未能找到解决方案。我很感激任何帮助。



var count = 0; // variables to hold random value and displacement
var i;
function stuff() {
  console.log("stuff");
}

function doThousandTimes() { //executes 1000 times
  while (count < 1000) {
    i = 0;
    timeout();
    count++;
  }
}

function timeout() { //executes 100 times
  setTimeout(function() {
    stuff();
    if (i < 100) {
      i++;
      timeout();
    }
  }, 100);
}
console.time("do1000");
doThousandTimes();
console.timeEnd("do1000");
console.time("timeout");
timeout();
console.timeEnd("timeout");
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

doThousandTimes中没有任何内容等待timeout完成一系列定时回调。您可以将回调传递给它在系列完成时调用的timeout,因此doThousandTimes可以继续下一个,请参阅评论:

&#13;
&#13;
var count = 0;
var i;
function stuff() {
  console.log("stuff: ", count, i);
}

function doThousandTimes(done) {
  if (count < 20) {
    // Update and call timeout, passing in a function
    // to use as its done callback that will
    // call doThousandTimes again
    count++;
    i = 0;
    // `bind` creates a function that will get done as an argument
    timeout(function() {
      doThousandTimes(done);
    });
  } else {
    // We're done -- call our done callback if any
    if (done) {
      done();
    }
  }
}

function timeout(done) {
  setTimeout(function() {
    stuff();
    if (i < 10) {
      i++;
      timeout(done);
    } else {
      // Done -- call our "done" callback, if any
      if (done) {
        done();
      }
    }
  }, 100);
}
// Note putting the `timeEnd`s and such *into* callbacks below
console.time("do1000");
doThousandTimes(function() {
  console.timeEnd("do1000");
  console.time("timeout");
  timeout(function() {
    console.timeEnd("timeout");
  });
});
&#13;
.as-console-wrapper {
  max-height: 100% !important;
}
&#13;
&#13;
&#13;

注意:我已将限制更改为count < 20(而不是count < 1000)和i < 10(而不是i < 100)只是这样片段可以运行完成。我还更新了stuff以显示当前的counti