如何访问JavaScript中的局部变量,特别是setInterval()和clearInterval()方法?
我正在用JS制作一个Pomodoro计时器 我使用的是“开始”和“停止”按钮。单击“开始”按钮时,计时器在25:00分钟开始计时,并下降到00:00分钟 我已经用Date对象和setInterval方法完成了这项工作。 我想要的是,如果用户想在25分钟前停止计时器,那么他们需要一个“停止”按钮 为此,我需要访问存储setInterval状态的变量x。这个x需要传递给clearIntervalx。这就是我停止计时器的方法 现在,, 我有两个单独的startTimer和stopTimer功能用于单独的按钮[onclick]。setInterval的状态,即变量x在startTimer函数中,而要停止计时器,我需要在另一个函数stopTimer中访问此局部变量 如何访问此局部变量 以下是相关代码:如何访问JavaScript中的局部变量,特别是setInterval()和clearInterval()方法?,javascript,scope,setinterval,Javascript,Scope,Setinterval,我正在用JS制作一个Pomodoro计时器 我使用的是“开始”和“停止”按钮。单击“开始”按钮时,计时器在25:00分钟开始计时,并下降到00:00分钟 我已经用Date对象和setInterval方法完成了这项工作。 我想要的是,如果用户想在25分钟前停止计时器,那么他们需要一个“停止”按钮 为此,我需要访问存储setInterval状态的变量x。这个x需要传递给clearIntervalx。这就是我停止计时器的方法 现在,, 我有两个单独的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.
}
在没有var的情况下分配x或在函数外部声明,以使作用域可用于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.
}
你把它放在外面。