在Javascript记分板上暂停计时器并不起作用

时间:2018-02-12 05:32:15

标签: javascript jquery timer setinterval clearinterval

我想知道如何解决我的问题。我希望我的记分板上的计时器在整数点击= 1时和空格键停止时启动,并在click = 2和空格键停止时暂停。当我尝试这样做时,每次按下它时都会调用函数commencing(),使计时器变得越来越快。这是代码示例:

var minutes = 0;
var c = 0;
var secondes = 0;
var click = 0;

        document.addEventListener("keydown", function(event) {

            switch (event.keyCode) {
                case 32:
                    click = click + 1;
                    if (click = 1) {
                       var commence = setInterval(commencing, 1000); 
                    } else if (click = 2) {
                       clearInterval(commence);
                       click = 0; 
                    }
                break;    
            }
    });

    function commencing(){  
                            secondes -= 1;
                            document.getElementById('temps').innerHTML = minutes + ":" + secondes;
                        if (secondes < 10) {
                            document.getElementById('temps').innerHTML = minutes + ":" + c + secondes;
                        }    
                        if (secondes < 1) {
                            secondes = 60;
                            minutes = minutes - 1;
                            if (minutes < 0) {
                                clearInterval(commencing);
                                minutes = 0;
                                secondes = 0;
                            }
                        }   
                      }

1 个答案:

答案 0 :(得分:0)

将函数外部的变量commence定义为全局变量。