对象计时器无法正常工作(暂停按钮,播放按钮)

时间:2018-12-28 09:59:07

标签: javascript oop object timer

我正在尝试设置对象Timer。实际上,当我单击“播放”按钮时,所有按钮都可以正常工作。

但是,当我试图暂停时(在console.log中),我的计时器每次点击返回-1(-2,-3等)。

如何防止这种情况?

class Timer{

    constructor(times){
        this.time = times;
        this.buttonPlay = document.getElementById('play')
        this.buttonPause = document.getElementById('pause')
        this.buttonStop = document.getElementById('stop')
        this.displayTimer = document.getElementById('timer')
    }

    decrementTime(){
        t.buttonPlay.addEventListener('click', function(){
            let checked = 0
            let s = setInterval(()=>{
                console.log(t.time[checked]--)
                if(t.time[checked]<0){
                    checked++;
                    console.log('checked = '+ checked)
                    if(checked === 3){
                        clearInterval(s)
                    }
                }
            }, 1000)
            t.buttonPause.addEventListener('click', function(){
                clearInterval(s);
            })
        })
    }
}

let t = new Timer([4, 7, 8]);
t.decrementTime()

1 个答案:

答案 0 :(得分:1)

获得“ -1”是因为每次单击播放时,程序都会从​​第一个元素开始检查。

为避免这种情况,只需将let checked = 0移动到事件监听器之外即可

class Timer {

    constructor(times) {
        this.time = times;
        this.buttonPlay = document.getElementById('play')
        this.buttonPause = document.getElementById('pause')
        this.buttonStop = document.getElementById('stop') //does nothing on this script
        this.displayTimer = document.getElementById('timer') //does nothing on this script
    }

    decrementTime() {
        let checked = 0
        t.buttonPlay.addEventListener('click', function () {
            let s = setInterval(() => {
                console.log(t.time[checked]--)
                if (t.time[checked] < 0) {
                    checked++;
                    console.log('checked = ' + checked)
                    if (checked === t.time.length) {
                        clearInterval(s)
                    }
                }
            }, 500)
            t.buttonPause.addEventListener('click', function () {
                clearInterval(s);
            })
        })
    }
}

let t = new Timer([4, 7, 8,50]);
t.decrementTime()
<button id="play">Play</button>
<button id="pause">pause</button>
<button id="stop" disabled>stop</button>
<button id="timer" disabled>timer</button>

编辑:我还更改了停止条件,以便能够处理任何长度的数组,并添加了一个更大的数组以用于测试