我正在用JS制作Pomodoro计时器。

我为此使用了“开始”和“停止”按钮。单击“开始”按钮时,计时器从25:00分钟开始计时,然后下降到00:00分钟。

我已经使用Date()对象和setInterval()方法完成了此操作。
我要的是如果用户要在25分钟之前停止计时器,则有一个“停止”按钮。

为此,我将需要访问存储x状态的变量setInterval()。该x需要传递给clearInterval(x)。这就是我停止计时器的方式。

现在,
我有2个单独的startTimer()stopTimer()函数用于单独的buttons[onclick]setInterval的状态,即变量xstartTimer()函数中,而要停止计时器,我需要在另一个函数stopTimer()中访问此局部变量

如何访问此局部变量?

以下是相关代码:

function startTimer() {

    var toDateTime = new Date().getTime() + 1500000; //adding 25 mins to current time
    console.log("startFunction is on with endDate: " + toDateTime);

    //use setInterval to update every second
    var x = setInterval(function() {
        timerFunc(toDateTime)
    }, 1000); //need to access this var x in stopTimer
} //end startTimer function


function stopTimer() {
    clearInterval(x); //can't access 'x' here, workaround this.
}

最佳答案

在没有x的情况下分配var或声明外部函数以使作用域可用于stopTimer函数

var x;
function startTimer(){

    var toDateTime = new Date().getTime() + 1500000;       //adding 25 mins to current time
    console.log("startFunction is on with endDate: "+toDateTime);
    //use setInterval to update every second
    clearInterval(x); //Clear interval before setInterval to prevent creation of multiple interval
    x = setInterval(function(){timerFunc(toDateTime)}, 1000); //need to access this var x in stopTimer
}//end startTimer function


function stopTimer(){
    clearInterval(x);    //can't access 'x' here, workaround this.
}

09-30 14:17
查看更多