admin管理员组文章数量:1240996
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.
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.
Thanks for all the help.
Mike
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.
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.
Thanks for all the help.
Mike
Share Improve this question asked Oct 9, 2014 at 5:40 mdumkamdumka 1351 gold badge1 silver badge4 bronze badges3 Answers
Reset to default 10When 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
counter()
setInterval
Update 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
var iter = 0;
function counter() {
console.log('show at ' + (iter++));
setTimeout(counter, 1000);
}
counter();
var i=0;
var timer;
function increement() {
if(i<100) {
console.log( 'Currently at ' + i )
} else {
clearInterval(timer);
}
i++;
}
timer = setInterval(function() {increement()}, 1000);
http://jsfiddle/pfq7a5n3/
本文标签: Javascriptdisplay incrementing number every secondStack Overflow
版权声明:本文标题:Javascript - display incrementing number every second - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740040354a2221662.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论