检测javascript循环内异步函数的结尾

问题描述 投票:0回答:1

我是新来的,请帮助我。我想检测javascript中for循环内异步函数的结尾。我的代码是:

  for (var i = 0; i < dataPoints.length; i++) {
  (function(i) {
    setTimeout(function() {


     if(end of everything)
     {
      //call xyz()
     }

    }, 5000 * i);
  })(i); 
}

请帮助我实现目标。谢谢

javascript for-loop asynchronous settimeout
1个回答
0
投票

您可以只检查i是否为数组的最后一个索引:

 dataPoints = [1, 2, 3]; 
 for (var i = 0; i < dataPoints.length; i++) {
  (function(i) {
    setTimeout(function() {
      console.log(i);

     if(i === dataPoints.length - 1) // if i is the last iteration
     {
      console.log('the end');
      //call xyz()
     }

    }, 1000 * i); // changed 5s to 1s for demo
  })(i); 
}

0
投票

使用您的设计,您检查超时是否是最后一个。

function xyz() {
  console.log("done");
}
var dataPoints = ["a", "b", "c", "d", "e"]

for (var i = 0; i < dataPoints.length; i++) {
  (function(i) {
    setTimeout(function() {
      console.log(i, dataPoints[i])      
      if (i === dataPoints.length - 1) {
        xyz()
      }
    }, 500 * i);
  })(i);
}

您最好使用队列

© www.soinside.com 2019 - 2024. All rights reserved.