倒数计时器不会停止

时间:2013-07-08 14:53:38

标签: javascript html5 canvas drawing

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

这是updated 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();

1 个答案:

答案 0 :(得分:0)

你应该把timer 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范围更改为窗口,因为小提琴没有找到它。这应该可以解决问题:

window.istop = function() {
    clearTimeout(timer);
    timer = null;
    return false;
}