如何用JS将计时器绑定到进度环?

时间:2013-09-16 15:19:42

标签: javascript timer settimeout

我正在玩一个进度环,我似乎无法让它在计时器上运行。我试图使进度环自动传播,比如0.5秒,从0%变为我设置的百分比(在这种情况下为65%)。

我使用此进度响铃作为基础:http://llinares.github.io/ring-progress-bar/

这是我的小提琴:http://jsfiddle.net/gTtGW/

我尝试使用计时器功能,但我可能没有正确地集成它。在小提琴中,我添加了:

for (var i = 0; i< 65; i++){
        range += i;
        setTimeout(timer,800);
    }

然而,这打破了进度环。我认为无论何时更新范围(使用+ = i),都会调用绘制函数。我究竟做错了什么?非常感谢你。

2 个答案:

答案 0 :(得分:0)

我想你想要这样的东西:

function inc() {
    var val = parseInt(range.value, 10)
    range.value = val + 1;
    draw(); // updating the value doesn't cause `onchange`.
    if (val < 100) { // don't go over 100
        setTimeout(inc, 100);
    }
}
inc();

答案 1 :(得分:0)

如果您不打算使用input[type=range]元素,可以将代码更改为:

(function (window) {
'use strict';

var document = window.document,
    ring = document.getElementsByTagName('path')[0],
    range = 0,
    text = document.getElementsByTagName('text')[0],
    Math = window.Math,
    toRadians = Math.PI / 180,
    r = 100;

function draw() {
    // Update the wheel giving to it a value in degrees, getted from the percentage of the input value a.k.a. (value * 360) / 100
    var degrees = range * 3.5999,
        // Convert the degrees value to radians
        rad = degrees * toRadians,
        // Determine X and cut to 2 decimals
        x = (Math.sin(rad) * r).toFixed(2),
        // Determine Y and cut to 2 decimals
        y = -(Math.cos(rad) * r).toFixed(2),
        // The another half ring. Same as (deg > 180) ? 1 : 0
        lenghty = window.Number(degrees > 180),
        // Moveto + Arcto
        descriptions = ['M', 0, 0, 'v', -r, 'A', r, r, 1, lenghty, 1, x, y, 'z'];
    // Apply changes to the path
    ring.setAttribute('d', descriptions.join(' '));
    // Update the numeric display
    text.textContent = range;
    range++;
    if(range > 100) {
        clearInterval(timer);
    }
}

  // Translate the center axis to a half of total size
  ring.setAttribute('transform', 'translate(' + r + ', ' + r + ')');

 var timer = setInterval(draw,100);

}(this));

基本上将range更改为从0开始的简单变量,并在每次调用draw()时增加其值。创建一个间隔(名为timer),在这种情况下每0.1秒运行一次(当然这取决于你),并在适当的时候从draw()清除该间隔...

JSFiddle Demo