1

So I have this code that I'm developing:

/**
 * Increment value with random intervals.
 * @param {string} id - Id of DOM Element.
 * @param {number} start - Start counter value. Applied immediately.
 * @param {number} end - End counter value.
 * @duration {number} duration - Max duration of one iteration in ms.
 */
function animateValue(obj, start, end, duration) {
  let current = start;
  obj.innerHTML = current; // immediately apply start value
  const setIncrOut = () => {
    let time = Math.random() * 1000;

    setTimeout(function() {
      if (current < end) {
        current += 1;
        obj.innerHTML = current;
        setIncrOut(time)
      }
    }, time);
  }
  setIncrOut();
}

document.querySelectorAll(".incr").forEach(obj => animateValue(obj, 10, 100000000));
<div class="incr"></div>

The above code always starts from 10.

What I want to achieve is to start between 0 and 10 randomly each time I run the script.

I have tried adding:

let srandom = Math.random();

and then changing to:

document.querySelectorAll(".incr").forEach(obj => animateValue(obj, srandom, 100000000));

But then the script doesn't show anything.

I guess I'm doing it wrong.

Any help would be appreciated.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
r0naldinio
  • 171
  • 6

2 Answers2

1

If you look at the MDN page for Math.random(), the very first example shows how to get a random number in a certain range.

Try this to get a number between 0 and 10:

let srandom = Math.floor(Math.random() * 11);
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
1

You could crate a function which will take 2 arguments (min and max) and get you a random number between these two numbers

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
spatak
  • 1,039
  • 1
  • 14
  • 25