For Loop无限运行

时间:2019-10-08 20:36:44

标签: javascript function loops for-loop

所以我已经与for循环战斗了一天半,当我得到它进行实际打印时,它就无限地运行了,即使if语句(logCount === 10)满足了... 不太确定要尝试什么,真的觉得它比我正在尝试的要简单得多。...

任何解决方案的尝试都值得赞赏。

var timers = [];

var log = (function(outputFunc) {

  var counter = 0;
  var callerLog = [];
  var dateTime = [];

  //assigning current Date to a variable to print for logs
  let logDate = new Date();
  return function(timer) {
    for (var logCount = 0; logCount <= 10; logCount++) {
      //printing data without using printFunc, as specified
      document.getElementById("output").innerHTML += logCount + " " + timer + " " + logDate + "<br>";

      //TODO: add after for loop is resolved.
      if (logCount >= 10) {
        clearInterval(timer1);
        clearInterval(timer2);
        clearInterval(timer3);
        document.getElementById("output").innerHTML += "<br><br/> Logging stopped.";
      }
    }
  }
})(printFunc);

function printFunc(output) {
  document.write(output + "<br>");
}

function startMeUp() {
  // add each of the timer references to the timers array
  // as part of invoking the log function following each interval
  timers.push(setInterval("log('Timer1')", 1000));
  timers.push(setInterval("log('Timer2')", 1200));
  timers.push(setInterval("log('Timer3')", 1700));
}

1 个答案:

答案 0 :(得分:0)

我猜这是您要实现的目标:

function printFunc(output) {
    // Replaced with console.log for my own convenience
    console.log(output);
}

// Not really a factory, just a curry of the outputFunc
function loggerFactory(outputFunc) {
    return function startLogger(name, interval) {
        // Variables to keep track of the iterations and a reference to the interval to cancel
        let logCount = 0;
        let intervalRef;

        function tick() {
            // On each tick, check if we're done
            // If yes, clear the interval and do the last output
            // If no, do some output and increment the iterator
            // Once the next tick passes we'll check again
            // If you were using setTimeout instead you would have to requeue the tick here
            if (logCount >= 10) {
                clearInterval(intervalRef);
                outputFunc('Done ' + name);
            } else {
                outputFunc(logCount + " " + name);
                logCount += 1;
            }
        }

        // Start it of
        intervalRef = setInterval(tick, interval);
    }
}

const logger = loggerFactory(printFunc);

function startMeUp() {
    console.log('Starting');
    logger('Log1', 1000);
    logger('Log2', 1200);
    logger('Log3', 1700);
}
startMeUp();

一些注意事项: 您可以将intervalRefs推送到一个数组中,但我发现将其工作封装在同一个logger中更好,因为它无论如何只能清理自身。

使用间隔(或通常为异步代码)进行循环时,通常不是您想要的。因为循环本质上是同步的,所以所有迭代将直接彼此直接运行,而没有其他空间。您正在寻找的是一种同时运行多个异步“轨道”的方法。您可以使用for循环来启动这些“轨道”,例如:

 for () {
   logger('Log' + i, 1000 * i);
 }

但是关键在于记录器快速设置间隔功能,然后返回。这样,您的for循环可以快速地“计划”任务,但是记录器可以使用setInterval或setTimeout在内部异步运行迭代。