我正在用JS制作Pomodoro计时器。
我为此使用了“开始”和“停止”按钮。单击“开始”按钮时,计时器从25:00
分钟开始计时,然后下降到00:00
分钟。
我已经使用Date()
对象和setInterval()
方法完成了此操作。
我要的是如果用户要在25分钟之前停止计时器,则有一个“停止”按钮。
为此,我将需要访问存储x
状态的变量setInterval()
。该x
需要传递给clearInterval(x)。这就是我停止计时器的方式。
现在,
我有2个单独的startTimer()
和stopTimer()
函数用于单独的buttons[onclick]
。 setInterval
的状态,即变量x
在startTimer()
函数中,而要停止计时器,我需要在另一个函数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.
}