如果条件停止javascript倒计时功能

时间:2017-02-09 09:18:40

标签: javascript function settimeout decrement

我有一个根据变量显示倒计时时钟的功能。什么是在指定条件下停止它的正确方法? clearTimeout不会停止递减函数。

function interface_vip(type){
    var timeout = '';
    var clock = '';
    //display clock
    function Decrement() {
        currentMinutes = Math.floor(secs / 60);
        currentSeconds = secs % 60;
        if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
            secs--;
            if(secs !== -1) timeout = setTimeout(Decrement,1000);
    }
    if (type == 1){
        var mins = 20;
        var secs = mins * 60;
        var currentSeconds = 0;
        var currentMinutes = 0;
        clock = setTimeout(Decrement,1000);
    }
    if (type == 2){
        clearTimeout(clock);
        clearTimeout(timeout);
    }
}

1 个答案:

答案 0 :(得分:2)

您的时钟ID在第二次调用时丢失,一个糟糕的解决方案是创建全局变量

    var timeout = '';
        var clock = '';
  function interface_vip(type){   
        //display clock
        function Decrement() {
            currentMinutes = Math.floor(secs / 60);
            currentSeconds = secs % 60;
            if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
                secs--;
                if(secs !== -1) timeout = setTimeout(Decrement,1000);
        }
        if (type == 1){
            var mins = 20;
            var secs = mins * 60;
            var currentSeconds = 0;
            var currentMinutes = 0;
            clock = setTimeout(Decrement,1000);
        }
        if (type == 2){
            clearTimeout(clock);
            clearTimeout(timeout);
        }
    }

在轰鸣声片段中采用更好的方法

function interface_vip(){
    var timeout = '';
    var t = 0;
    var clock = '';
    //display clock
    function Decrement() {
        currentMinutes = Math.floor(secs / 60);
        currentSeconds = secs % 60;
        if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
            secs--;
            if(secs !== -1) timeout = setTimeout(Decrement,1000);
    }
   this.start = function(){
        var mins = t;
        var secs = mins * 60;
        var currentSeconds = 0;
        var currentMinutes = 0;
        clock = setTimeout(Decrement,1000);
    }
    this.stop = function(){
        clearTimeout(clock);
        clearTimeout(timeout);
    }
}
var interf = new interface_vip();
interf.start();
interf.stop();