Javascript - display incrementing number every second

前端 未结 3 1303
清歌不尽
清歌不尽 2020-12-10 22:29

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

<
相关标签:
3条回答
  • 2020-12-10 23:19
        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/

    0 讨论(0)
  • 2020-12-10 23:24

    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
    
    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
    
    0 讨论(0)
  • 2020-12-10 23:26
    var iter = 0;
    function counter() {
        console.log('show at ' + (iter++));
        setTimeout(counter, 1000);
    }
    
    counter();
    
    0 讨论(0)
提交回复
热议问题