如何在 javascript 的嵌套 for 循环中添加超时 fn?

How to add timeout fn in nested for loop in javascript?

我有这样的代码:

    balls_delivery1 = [6, 7, 8, 6, 6] // balls in a over(cricket match)
    // above 6 balls in 0th over so the counter(key) below will be till 0.6 
     //and then 1.1 to 1.7 and so on
    deliveries1 = [{
    '0.1': {    // 0.1 is 0th over 1st ball
      batsman: 'MEK Hussey',
      bowler: 'IK Pathan',
      non_striker: 'S Badrinath',
      runs: [Object]
    }
  },{}... so on many objects]
     



for (i=0; i<balls_delivery1.length; i++){
     for (j=0; j<balls_delivery1[i]; j++){
        // i is over j is ball
         console.log(`${i} over ${j+1} ball , ${i}.${j+1}`);
         console.log(Object.values(deliveries1[j])[0]);
         // I want to show the above lines every 5 sec
      }
  }

请帮忙,我无法从 Whosebug 上的答案中解决它。

在循环内使用函数设置超时,像这样;

(function(){setInterval(() => console.log('hello'), 5000)})()

你的意思是,你想每 5 秒打印 70 个问候?因为这就是您使用循环解决方案时发生的情况。不要这样!

for (i=0; i<10; i++){
    for (j=0; j<7; j++){
        console.log('hello');  // I want to print this hello every 5 seconds
    }
}

或者您只是想每 5 秒打印一次 hello 并试图用循环解决这个问题?

这是通常每 5 秒打印一次 hello 的方法

// start the interval and memorize it
const interval = setInterval( () => {

    console.log('hello');

}, 5000);


// stop the interval somewhere else in your code
clearInterval(interval);

如果您在此处使用循环,则必须有一个数组来存储所有 70 个间隔,以便在必要时有机会停止它们。我无法想象这就是你想要的。

你可以试试这样的方法。

for (i=0; i<10; i++){
  (function(index_i) {
      setTimeout(function() {
        for (j=0; j<7; j++){
          (function(index_j) {
              setTimeout(function() { console.log('hello ' + index_i + ' - ' + index_j); }, j * 5000);
          })(j);
        }
      }, i * 7 * 5000);
  })(i);
}

function testTimeout(){
    function consoleHello(i){
    setTimeout(function(){console.log('Hello' + i);}, 800*i); //setTimeout for 800ms
  }
  
    for (var i=0; i<10; i++){
      consoleHello(i);
  }
}

这很简单 - 在循环中使用 setTimeout 的工作代码。让我更新您代码的答案

工作代码段的es6 variant

for (let i=0; i<=10; i++) {
    setTimeout(() => {console.log(i);}, 1000 * i);
}