user7184660
user7184660

Reputation:

How to make a JS Counter & Reset?

I am trying to make a JS counter to reach a random number and reset it self once it reaches the number and repeat again in 5 seconds.

For example: Random Number is 0.05.

0.00 > 0.01 > 0.02 > 0.03 > 0.04 > 0.05 > 0.00

<div id="current">0</div>

JS

var randomNum = Math.random();

if ( current <= randomNum ) {
    for (current = 0; current < randomNum; current+=0.01) {
        setInterval(function(){
            current += .01;
        },1000);    } }
    else {
        current = 0;
    }

Upvotes: 1

Views: 602

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386848

You could use a closure over the variables and make a check inside of the callback, if greater then the wanted result.

This proposal uses setInterval for counting and setTimeout for the waiting time of 5 sec and the restarting with a new random value.

function startInterval() {
    var randomNum = Math.floor(Math.random() * 8) + 2,
        current = 0,
        interval = setInterval(function() {
            current += .01;
            if (current > randomNum / 100) {
                current = 0;
                clearInterval(interval);
                setTimeout(startInterval, 5000);
            }
            document.getElementById('current').innerHTML = current.toFixed(2);
        }, 1000);
}

startInterval();
<div id="current">0</div>

Upvotes: 1

Emil S. J&#248;rgensen
Emil S. J&#248;rgensen

Reputation: 6366

Keep a counter variable outside of the loop and then simply clear it, when the desired value is reached.

var randomNum = Math.random() * 25;
var currentValue = 0;
var counter;
counter = setInterval(function() {
  if (currentValue < randomNum) {
    //Carefull with "0.1" as JavaScript doesn't like it!
    currentValue = (currentValue * 10 + 1) / 10
  }
  if (currentValue > randomNum) {
    currentValue = randomNum;
    clearInterval(counter);
  }
  console.log(currentValue, '/', randomNum)
}, 1000 / 60)

Upvotes: 1

Related Questions