0

如何让进度条根据计数器值更改“速度”或 setInterval?因此,例如,如果条形小于 40 - 执行此操作,或小于 60 执行此操作,依此类推。

我试图在进度条达到 40 后减慢进度条,然后再减至 60%。

var counter = 0;
var timer = setInterval(function () {
        if (counter <= '40') {
            progressLoading.val(counter);
            counter = counter += 1;
        } else {
            clearInterval(timer);
        }
    }, 20);
4

1 回答 1

1

在控制台中运行以下命令,看看是不是你想要的效果。

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);

最初,counter增加factor = 1. 之后40factor逐渐减小。的最小值factor不能小于minVal

显示出更多不规则性的进展 -

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函数总是返回一个 到 之间的-1数字+1。我们只需要正数,所以我们通过Math.abs. 这使得factor总是介于0和之间1

此外,数字可能太小,因此因子值可能微不足道。为确保不会发生这种情况,我们将最小值设置为0.1,由 进行检查Math.max

显示进度不规则和速度下降 -

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);

这一个是上述两者的结合。在第二个中,factor可以是 和 之间的任何0内容1。上面的函数确保factor介于0和之间,我们从使用 1中使用的阻尼函数maxVal不断减少。maxVal10.1

于 2013-10-10T20:44:26.827 回答