window.onload = function() {
console.log("Hello");
var button = document.getElementById("animateButton");
button.onclick = goProgress;
}
function goProgress() {
console.log("In goProgress()");
var progressBars = document.getElementsByClassName("progress");
for(var i=0;i<progressBars.length;i++){
console.log("Progress Bar " + (i+1) + ": " + progressBars[i]);
setInterval(increaseVal(progressBars[i]),10);
}
};
function increaseVal(progressBar){
console.log("In increaseVal(): " + progressBar.value);
if(progressBar.value<100){
progressBar.value = progressBar.value + 1;
}
}
<progress class="progress" value="20" max="100"></progress>
<br>
<progress class="progress" value="0" max="100"></progress>
<br>
<progress class="progress" value="30" max="100"></progress>
<br>
<br>
<input type="button" value="Animate" id="animateButton"/>
setInterval
takes a function as first parameter, you're actually calling the function, you have to only pass the reference.
According to the documentation any parameters after the delay will be passed to the function.
setInterval(increaseVal, 10, progressBars[i]);
To clear the interval once it reaches 100 you will have save the intervalId, the easiest would probably be just writing it to the progressbar.
progressBars[i].interval = setInterval(increaseVal, 10, progressBars[i]);
// snip
function increaseVal(progressBar){
console.log("In increaseVal(): " + progressBar.value);
if (progressBar.value < 100) {
progressBar.value = progressBar.value + 1;
} else {
clearInterval(progressBar.interval);
}
}
You could obviously also save them in a custom array but then you will have to pass the array index to the function.
Check the jsfiddle here
With setInterval()
you can pass the parameters to the function you want to repeatedly call as the arguments after the delay. Then you can use an array to hold the clearInterval handles for each element with clr[i] = setInterval(increaseVal, 10, progressBars[i],i);
:
Example:
window.onload = function() {
console.log("Hello");
var button = document.getElementById("animateButton");
button.onclick = goProgress;
}
var clr = [];
function goProgress() {
console.log("In goProgress()");
var progressBars = document.getElementsByClassName("progress");
for (var i = 0; i < progressBars.length; i++) {
console.log("Progress Bar " + (i + 1) + ": " + progressBars[i]);
clr[i] = setInterval(increaseVal, 10, progressBars[i],i);
}
};
function increaseVal(progressBar,i) {
console.log("In increaseVal() " + i + ": " + progressBar.value);
if (progressBar.value < 100) {
progressBar.value = progressBar.value + 1;
} else {
clearInterval(clr[i])
}
}
<progress class="progress" value="20" max="100"></progress>
<br>
<progress class="progress" value="0" max="100"></progress>
<br>
<progress class="progress" value="30" max="100"></progress>
<br>
<br>
<input type="button" value="Animate" id="animateButton" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With