如何阻止我的javascript倒计时?

时间:2012-03-30 18:53:34

标签: javascript

如何在倒数= 0时停止我的javascript功能?

JS:

var settimmer = 0;
$(function(){
  window.setInterval(function() {
      var timeCounter = $("b[id=show-time]").html();
      var updateTime = eval(timeCounter)- eval(1);
      $("b[id=show-time]").html(updateTime);
    }, 1000);
});

HTML:

<b id="show-time">20</b>

6 个答案:

答案 0 :(得分:4)

一件事删除那些eval。他们什么都不做。

然后你所要做的就是在计时器到达零时清除它。

$(function(){
        var timer = setInterval(function() {
            var timeCounter = parseInt($("b[id=show-time]").text());
            $("b[id=show-time]").text(--timeCounter); // remove one
            if(!timeCounter) clearInterval(timer);
        }, 1000);
});

答案 1 :(得分:2)

很容易!当您致电setInterval时,它会返回一个ID,因此您可以稍后销毁该间隔。为了摧毁它,你必须使用clearInterval(id)和il!

答案 2 :(得分:1)

它的工作原理如下:

// Activate timer
var iv = window.setInterval(...);

// Deactive timer
window.clearInterval(iv);

另外你应该使用parseInt()而不是eval():

$(function() {
    // Read the start value once and store it in a variable
    var timeCounter = parseInt( $("b[id=show-time]").text() );

    // Active the counter
    var iv = window.setInterval(function() {
        // Decrement by one and write back into the document
        $("b[id=show-time]").text(--timeCounter);

        // Check if counter == 0 -> stop counting
        if (0 == timeCounter) {
            window.clearInterval(iv);
            // ...do whatever else needs to be done when counter == 0 ..
        }
    }, 1000);
});

答案 3 :(得分:0)

示例:

var i = 0,
    pid = setInterval(function() {
        if (++i > 10)
            clearInterval(pid);
    }, 1000);

根据您对代码的要求......

$(function() {
    var el  = document.getElementById('show-time'),
        pid = setInterval(function() {
            // (s - i) coerces s to Number
            var t = el.innerHTML - 1;
            el.innerHTML = t;
            if (t < 1)
                clearInterval(pid);
        }, 1000);
});

答案 4 :(得分:0)

请记住,JS的时机不会100%准确。

粘贴下面的代码或查看小提琴:http://jsfiddle.net/raHrm/

<script type="text/javascript">
$(function(){

var settimmer = 0,
    timeCounter = $("#show-time").html(),
    updateTime = timeCounter;

(function countDown() {
    timeCounter = $("#show-time").html();
    updateTime = parseInt(timeCounter)-1;
    $("#show-time").html(updateTime);
    if ( updateTime ) {
        setTimeout(countDown, 1000);
    }
})();

});​
</script>

答案 5 :(得分:0)

将计时器设置为变量,然后按顺序使用clearInterval来停止循环。至于结束,使用一个简单的条件:

$(function(){
    var elem=$('strong[id="show-time"]'),settimmer=0,updateTime,t;
    t=window.setInterval(function() {
        updateTime=parseFloat(elem.html(),10)-1;
        if(updateTime==0) {
            window.clearInterval(t);
            elem.html('Done!');
        } else {
            elem.html(updateTime);
        }
    },1000);
});

然后在HTML中:

<strong id="show-time">20</strong>

<b>代码已弃用,请尽量避免使用它。此外,没有理由eval()从元素中获取HTML;一个简单的parseFloat()就可以了。