停止 JavaScript 倒计时函数 if 条件



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

最新更新