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.