【发布时间】:2019-10-08 20:36:44
【问题描述】:
所以我已经与这个 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));
}
【问题讨论】:
-
这段代码的目的是什么?
-
为什么要将字符串传递给 setInterval ?
-
我在此处提供的代码中唯一能看到的是
clearInterval永远不会工作,因为从未定义过timer1、timer2和timer3。那,printFunc将擦除整个页面,这可能导致document.getElementById开始抛出空指针异常。但是,for循环应该在运行 11 次后正确终止。如果有的话,从这里的代码来看,我希望它会因为错误而更快地完成。尽管由于setIntervals,它可能会永远重新运行 -
你的代码没有意义。您正在将字符串传递给 setInterval 函数,并且没有声明您要清除的任何计时器。
-
我的教授给了我这个代码 lmao 谢谢大家,很明显是被窃听了,哈哈,都修好了,谢谢,真的是在浪费我的时间
标签: javascript function loops for-loop