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.

2
  • 1
    console.log(srandom) or debug and inspect the value. You'll see that it's a number between 0 and 1. Commented Aug 27, 2021 at 13:17
  • setTimeout is not made to respect his delay argument... Commented Aug 27, 2021 at 13:23

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

If the minimum is always zero there's really no reason to have a minimum argument at all.
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);

1 Comment

We have many many many questions about getting random numbers between two numbers...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.