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

问题描述

我有这样的代码

    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
      }
  }

请帮忙,我无法从 stackoverflow 上的 ans 解决它。

解决方法

你可以试试这样的。

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);
}

,

在setTimeout的循环内使用函数,像这样;

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

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

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 个间隔,以便在必要时有机会停止它们。我无法想象这就是您想要的。

,

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);
}