繁体   English   中英

Javascript - 每秒显示递增的数字

[英]Javascript - display incrementing number every second

我正在尝试做一些事情,每秒显示一个不同的递增数字,但我无法正确设置 setInterval 。

这是我所拥有的

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 次,然后重复。

感谢所有的帮助。

麦克风

当您创建一次 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 counter()

设置间隔

更新 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.net/pfq7a5n3/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM