1

如果在 10 秒之前给出答案,我需要一个停止功能。我尝试了一些想法,但找不到解决方案

这是更新的 jsFiddle和我的代码。有人可以帮忙吗?

HTML

<canvas id="timer" width="48" height="48"></canvas>
<span id="num"></span>

<br /><br />
<a href="javascript:istop();">stop</a>

JAVASCRIPT

function sCounter(){
    canvas = document.getElementById('timer');
    num = document.getElementById('num');
    ctx = canvas.getContext('2d');
    fps= 40;

    var total = fps*10; //*second
    for(var i=total;i>=0;i--) {
        var delayed = (function(){
            var step = 1-i/total;
            var left = Math.ceil(i/fps);
            return function() {
                num.innerHTML=left;
                draw_next(step);

                if(left===0){  //if 0
                    //etc...
                }
            };
        })();
        var timer = setTimeout(delayed,-1000/fps*(i-total));
    }
}

function draw_next(step) {
    ctx.clearRect(0,0,48,48);
    ctx.beginPath();
    ctx.arc(24,24,20,Math.PI * (-0.5 + 0),Math.PI * (-0.5 + step*2),false);
    ctx.lineWidth = 8;
    ctx.strokeStyle = "#dedede";
    ctx.stroke();
}

function istop(e) {
    e.preventDefault();
    var timer = null;
    clearTimeout(timer);
    return false;
}

sCounter();
4

1 回答 1

0

您应该将计时器 var 放在一个公共范围内,似乎 for 循环正在激活计时器而前一个已结束,因此您无法清除它们,请参阅 de fiddle:http: //jsfiddle.net/ HQJkz/

    var timer = null

    function sCounter() {
    canvas = document.getElementById('timer');
    num = document.getElementById('num');
    ctx = canvas.getContext('2d');
    fps = 40;

    var total = fps * 10; //*second

    var render = function (left, step, i) {
        num.innerHTML = left;
        draw_next(step);
        if (left)
        if (left === 0) { //if 0
            //etc...
        } else {
            delayed(i - 1);
        }
    };

    var delayed = function (i) {
        var step = 1 - i / total;
        var left = Math.ceil(i / fps);
        var current = function () {
            console.log(left, step);
            render(left, step, i);
        };
        timer = setTimeout(current, -1000 / fps * (i - total));
    }

    delayed(total - 1);
}

而且您似乎在失去价值后试图清除计时器。我不得不将 istop 范围更改为窗口,因为 fiddle 没有找到它。这应该可以解决问题:

window.istop = function() {
    clearTimeout(timer);
    timer = null;
    return false;
}
于 2013-07-08T14:54:41.563 回答