'JavaScript: how to control progress speed?
Is there any option to increase and decrease the speed of the progress? Sometimes progress takes time and sometime very slow to finish:
var value = 0,
interval = setInterval(function() {
value = ((+value) + .1).toFixed(1);
if(value == 80.5) clearInterval(interval);
$('p').html(value+'%');
},2);
Solution 1:[1]
You'll note that your code is using setInterval(). This global JavaScript function is used for periodically executing code at a given time interval. It takes two arguments for its typical usage (which is the way you are using it here). It returns a unique ID that can be used to identify your particular interval function (since multiple ones can be set up simultaneously).
The first argument is a function to be executed on the interval. Your function is the anonymous function:
function() {
value = ((+value) + .1).toFixed(1);
if (value == 80.5) clearInterval(interval);
$('p').html(value + '%');
}
This function will increase the percentage progress on each execution.
The second argument is an integer number for the number of milliseconds (thousandths of a second) to let elapse before the function from the first argument is executed. This is the key part for your question, I believe. Your code has 2 (on the last line of your posted code), so it will wait 2 milliseconds before executing your function (which increments the percentage progress), and then it will wait 2 more milliseconds, then execute the same function again, etc.
By simply changing the value of the second argument, you can change how fast or slow your function executes each time, which changes how fast or slow your percentage increases. So if you set it to 500, then setInterval will wait for a half a second before each execution of the function.
You can read about the other JavaScript timer functions here, in particular about clearInterval(), which your code uses in the anonymous function to end the interval when you reach 80.5%.
Solution 2:[2]
I hope this helps:
$(function(){
var value1 = 0;
var value2 = 0;
var span1 = $('#val1');
var span2 = $('#val2');
var interval1 = setInterval(function(){
span1.text(++value1);
if (value1 === 80) {
clearInterval(interval1);
clearInterval(interval2);
interval1 = null;
interval2 = null;
span2.text(5);
}
}, 100); // you can change speed here
var interval2 = setInterval(function() {
span2.text(value2++ % 10);
}, 70);
});
HTML:
<body>
<div class="progress-bar"></div>
<hr>
<p><span id="val1">0</span>.<span id="val2">1</span>%</p>
</body>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ikrom |
