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

stop javascript countdown function if condition

我有一个根据变量显示倒计时时钟的函数。在指定条件下停止它的正确方法是什么? 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);
    }
}

您的时钟 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();