重置javascript中的倒计时

时间:2012-09-04 22:13:33

标签: javascript jquery

我希望用户在输入运行重置倒计时后每次输入,我添加clearTimeout但它不起作用。我该怎么办? (请在我的代码中帮助我,我不需要新的代码。)

DEMO: http://jsfiddle.net/qySNq/

HTML:

<input id="MizMah">
<div id="Seconds" style="font-size: 80px;">5</div>​


Js代码:

$('#MizMah').live('keyup', function () {
    function render(n) {
        var digits = [],
            r;
        do {
            r = n % 10;
            n = (n - r) / 10;
            digits.unshift([r].join(''));
        } while (n > 0);
        $('#Seconds').html(digits.join(''));
    }

    (function timer(current) {
        render(current);
        if (current > 0) {
            myTimeout = setTimeout(function () {
                timer(current - 1);
            }, 1100);
            clearTimeout(myTimeout);
        }
    }(5));
})​

1 个答案:

答案 0 :(得分:2)

您在设置后立即清除了超时。试试这个:

var myTimeout = null;

$('#MizMah').live('keyup', function () {
    function render(n) {
        var digits = [],
            r;
        do {
            r = n % 10;
            n = (n - r) / 10;
            digits.unshift([r].join(''));
        } while (n > 0);
        $('#Seconds').html(digits.join(''));
    }

    (function timer(current) {
        render(current);
        if (current > 0) {
            clearTimeout(myTimeout);
            myTimeout = setTimeout(function () {
                timer(current - 1);
            }, 1100);
        }
    }(5));

})