Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - display incrementing number every second

Tags:

javascript

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

like image 219
mdumka Avatar asked Nov 08 '25 04:11

mdumka


2 Answers

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
like image 85
nikodz Avatar answered Nov 10 '25 18:11

nikodz


var iter = 0;
function counter() {
    console.log('show at ' + (iter++));
    setTimeout(counter, 1000);
}

counter();
like image 27
John V Avatar answered Nov 10 '25 17:11

John V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!