Javascript - 每秒显示递增的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26271084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - display incrementing number every second
提问by mdumka
I am trying to do something where I display a different incremented number every second but I just can't get the setInterval thing right.
我正在尝试做一些事情,每秒显示一个不同的递增数字,但我无法正确设置 setInterval 。
Here is what I have
这是我所拥有的
function counter() {
var i = 0;
while ( i < 100 ) {
// This block will be executed 100 times.
setInterval(console.log( 'Currently at ' + i ), 1000);
i++; // Increment i
}
} // End
But what I get is the console.log firing a 100 times, then repeating.
但我得到的是 console.log 触发 100 次,然后重复。
Thanks for all the help.
感谢所有的帮助。
Mike
麦克风
回答by nikodz
When you create a setInterval once, it will automatically call function (first argument) every 1000milliseconds (second argument). So you don't need to do it inside while, just put incrementing of iinside the function (first argument).
当您创建一次 setInterval 时,它会每1000毫秒(第二个参数)自动调用函数(第一个参数)。所以你不需要在 while 里面做,只需i在函数内部(第一个参数)添加增量。
function counter() {
var i = 0;
// This block will be executed 100 times.
setInterval(function(){
if (i == 100) clearInterval(this);
else console.log( 'Currently at ' + (i++) );
}, 1000);
} // End
Update 1
更新 1
function counter() {
var i = 0;
var funcNameHere = function(){
if (i == 100) clearInterval(this);
else console.log( 'Currently at ' + (i++) );
};
// This block will be executed 100 times.
setInterval(funcNameHere, 7000);
funcNameHere();
} // End
回答by John V
var iter = 0;
function counter() {
console.log('show at ' + (iter++));
setTimeout(counter, 1000);
}
counter();
回答by user733421
var i=0;
var timer;
function increement() {
if(i<100) {
console.log( 'Currently at ' + i )
} else {
clearInterval(timer);
}
i++;
}
timer = setInterval(function() {increement()}, 1000);

