预期输出:这里是消息1这里是消息2这里是消息3这里是消息4这里是消息5
实际输出:这里是消息1,这里是消息2,这里是消息3,这里是消息4
let i = 1;
const myInterval = setInterval(function() {
console.log('Here is message ' + i);
i = i + 1;
}, 2000);
// clear interval after specified time
setTimeout(function() {
clearInterval(myInterval);
}, 10000);发布于 2021-01-03 22:08:28
以下是基于上述注释的一些代码。我认为你的代码有一个有效的目的(有一些调整),但我认为它可能没有解决你的问题或情况的特定目的。总是尝试寻找最简单的解决方案。我推荐的一件事是,如果只递增1,那么可以直接执行i++,而不是执行i = i + 1。
let i = 1;
const max = 5;
const mytimer = setInterval(function () {
if (i <= max) {
console.log("Here is message " + i);
i++;
} else {
console.log("end of timer");
clearInterval(mytimer);
}
}, 2000);https://stackoverflow.com/questions/65550083
复制相似问题