我有一个构造函数(或类,如果你愿意),我的部分代码正在运行一个间隔。我试图清除间隔,但countDown
函数无法访问countDown
变量。
请注意: countDown
和startTimer
函数都在构造函数中。
以下是代码:
this.startTimer = function() {
if (!isOn) {
timeFormatter();
if (timeArray[0] === "0") {
return error(" You need to work longer than that! ")
}
isOn = true;
var startCountDown = setInterval(this.countDown.bind(this),1000);
}
}
this.countDown = function() {
//Once timer ends, stop function.
if (timeArray[0] === 0
&& timeArray[2] === 0
&& timeArray[3] === 1) {
element.innerHTML = 0;
counter = 0;
isOn = false;
clearInterval(startCountDown) //I get error here. countDown is not accessible.
return null;
}
}
答案 0 :(得分:-1)
您只需在功能对象中存储倒计时,然后将其绑定到此,而不是
this.countdown = setInterval()
然后将函数绑定到 this 。
this.startTimer = function(){
if(!isOn){
timeFormatter();
if(timeArray[0] === "0"){
return error(" You need to work longer than that! ")
}
isOn = true;
this.countDown = setInterval(this.countDown.bind(this),1000);
}
}.bind(this); // this
this.countDown = function () {
//Once timer ends, stop function.
if (timeArray[0] === 0 && timeArray[2] === 0 && timeArray[3] === 1) {
element.innerHTML = 0;
counter = 0;
isOn = false;
clearInterval(this.countdown);
return null;
}
}.bind(this); // and this one
将变量存储在更高级别
var countDown; // this
this.startTimer = function(){
if(!isOn){
timeFormatter();
if(timeArray[0] === "0"){
return error(" You need to work longer than that! ")
}
isOn = true;
countDown = setInterval(this.countDown.bind(this),1000);
}
}
this.countDown = function () {
//Once timer ends, stop function.
if (timeArray[0] === 0 && timeArray[2] === 0 && timeArray[3] === 1) {
element.innerHTML = 0;
counter = 0;
isOn = false;
clearInterval(countDown) //I get error here. countDown is not accessible.
return null;
}
}
希望有所帮助