Javascript - 每秒显示递增的数字 [英] Javascript - display incrementing number every second
本文介绍了Javascript - 每秒显示递增的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试做一些事情,我每秒都会显示不同的递增数字但是我无法正确地获得setInterval。
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.
这是我的拥有
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
但我得到的是console.log触发100次,然后重复。
But what I get is the console.log firing a 100 times, then repeating.
感谢所有帮助。
Mike
推荐答案
当你创建一次setInterval时,它会自动调用函数(第一个参数)每 1000
毫秒(第二个参数)。所以你不需要在里面做,只需在函数(第一个参数)中增加 i
。
When you create a setInterval once, it will automatically call function (first argument) every 1000
milliseconds (second argument). So you don't need to do it inside while, just put incrementing of i
inside the function (first argument).
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
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
这篇关于Javascript - 每秒显示递增的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文