As I work on developing this code, I am faced with a challenge:
/**
* 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 block of code above always initiates from the number 10.
I am working towards being able to randomly select a starting point between 0 and 10 each time the script runs.
I attempted adding:
let srandom = Math.random();
and then making changes to:
document.querySelectorAll(".incr").forEach(obj => animateValue(obj, srandom, 100000000));
However, this resulted in the script not displaying anything.
I believe there may be an error in my approach.
Your assistance is greatly appreciated.