Reputation:
How can I get the progress bar to change 'speed' or setInterval depending on the counter value? So for instance if the bar is less than 40 - do this, or less than 60 do that, and so on.
I'm trying to slow down the progress bar after it gets to 40, and then furthermore at 60 percent.
var counter = 0;
var timer = setInterval(function () {
if (counter <= '40') {
progressLoading.val(counter);
counter = counter += 1;
} else {
clearInterval(timer);
}
}, 20);
Upvotes: 0
Views: 1121
Reputation: 871
Run the following in the console and see if this is the effect you want.
var counter = 0;
var factor = 1;
var damping = 80; // Increase this to slow down increment.
// This is the minimum value of 'factor'. Increasing this will speed up the function
var minVal = 0.1;
var timer = setInterval(function () {
console.log(Math.ceil(counter)); // Call your function here.
counter = counter + factor;
if (counter > 40 && counter < 100) {
factor = Math.max((100 - counter)/damping, minVal)
} else if (counter > 100) {
clearInterval(timer);
}
}, 20);
Initially, counter
is being incremented by factor = 1
. After 40
, the factor
is gradually reduced. The minimum value of factor
cannot be less than minVal
.
Showing progress with more irregularity -
var counter = 0;
var factor = 1;
var timer = setInterval(function () {
console.log(Math.ceil(counter)); // Call your function here.
counter = counter + factor;
if (counter > 40 && counter < 100) {
factor = Math.max(Math.abs(Math.sin(100 - counter)), 0.1)
} else if (counter > 100) {
clearInterval(timer);
}
}, 20);
Math.sin
function always returns a number between -1
to +1
. We need only positive, so we pass it through Math.abs
. This makes factor
to always be between 0
and 1
.
Also, the number might be way too small and hence the factor value maybe insignificant. To make sure this doesn't happen, we have set a minimum value as 0.1
, which is checked by Math.max
.
Showing progress with irregularity and decreasing speed -
var counter = 0;
var factor = 1;
var maxVal = 1; // Maximum value of `factor` after crossing 40
var minVal = 0.1; // Minimum value of `maxVal`
var damping = 60; // damping for `maxVal`
var timer = setInterval(function () {
console.log(Math.ceil(counter)); // Call your function here.
counter = counter + factor;
if (counter > 40 && counter < 100) {
maxVal = Math.max((100 - counter)/damping, minVal)
factor = Math.min(Math.max(Math.abs(Math.sin(100 - counter)), 0.1), maxVal);
} else if (counter > 100) {
clearInterval(timer);
}
}, 20);
This one is both of the above combined. In the second one, factor
could be anything between 0
and 1
. The above function makes sure that factor
is between 0
and maxVal
and we keep decreasing maxVal
from 1
to 0.1
using the damping function used in 1.
Upvotes: 1