1

Im looking for a way to change the way my javascript number counter is working. Now it just counts up every second but I want it to count at random times between 1 second and 15 seconds.

function startCount(){
    timer = setInterval (count, 1000);  
}

function count(){
    var el = document.getElementById('counter');
    var currentNumber = parseFloat(removeCommas(el.innerHTML));
    el.innerHTML = addCommas(currentNumber+1);
}

function addCommas(nStr){
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;

    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }

    return x1 + x2 + '.00';
}

function removeCommas(aNum){
    //remove any commas
    aNum=aNum.replace(/,/g,"");

    //remove any spaces
    aNum=aNum.replace(/\s/g,"");

    return aNum;
}

Can someone help me change the count time to random numbers?

Zinnhead
  • 45
  • 4
dwayneE
  • 37
  • 5

3 Answers3

1

Assuming the interval is between 1 and 15 seconds and changed after each interval. setIntervsal() does not fit. setTimeout() is here a good choice, because of the single interval of waiting. Every next interval gets a new time to wait and has to be called again. The random waiting time is archieved through Math.random(), a function whicht returns floating points numbers between 0 and 1. With a factor and forced to integer and a padding of 1000 milli second we get the wanted interval.

(A word to former solution: first, i thought just a fixed random interval will suit, but the question ariesed, what kind of interval is requested.)

function startCount() {
    setTimeout(count, 1000 + Math.random() * 14000 | 0);
}
function count() {
    var el = document.getElementById('counter');
    var currentNumber = parseFloat(removeCommas(el.innerHTML));
    el.innerHTML = addCommas(currentNumber + 1);
    startCount();
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Try

(Math.floor(Math.random() * 15) + 1)*1000 instead of the fixed 1000ms

Generate random number between two numbers in JavaScript

Community
  • 1
  • 1
Michel Feldheim
  • 17,625
  • 5
  • 60
  • 77
0

Use setTimeout instead of setInterval in startCount() with a random time parameter, and call it at the end of count function.

function startCount()
{   
    timer = setTimeout (count, Math.floor(Math.random() * 14000) + 1000);  
}


function count()
{
    var el = document.getElementById('counter');
    var currentNumber = parseFloat(removeCommas(el.innerHTML));
    el.innerHTML = addCommas(currentNumber+1);
    startCount()
}
Roland Szabo
  • 153
  • 5