TypeScript - 变量分配上的 SetTimeOut 错误
TypeScript - SetTimeOut bug on variable assign
我正在使用 Ionic,Angular 这意味着我正在使用 TypeScript 语言。
我有一个布尔值,如果单击某个元素并且相同的布尔值是 true
,它应该变为 false
。在布尔值变为假后,运行 setTimeOut()
函数,以便在 5000 毫秒后布尔值再次变为 true
。
我面临的问题是运行 setTimeOut()
时。布尔值变为 true
。但是,当我再次单击该元素时(5000 毫秒后),布尔值是 false
...
代码在哪:
resendSMS() {
console.log('allowResendSMS: ', this.allowResendSMS);
if (this.allowResendSMS) {
this.allowResendSMS = false;
console.log('SMS HAS BEEN RESENDED');
console.log('allowResendSMS: ', this.allowResendSMS);
setTimeout(function () {
this.allowResendSMS = true;
console.log('END OF TIMEOUT');
console.log('allowResendSMS: ', this.allowResendSMS)
}, 5000);
}
}
输出在哪里:
(First Click on Element)
allowResendSMS: true
SMS HAS BEEN RESENDED
allowResendSMS: false
END OF TIMEOUT
allowResendSMS: true
(Second Click on Element)
allowResendSMS: false
END OF TIMEOUT
allowResendSMS: true
有人可以提供线索,说明为什么 allowresendSMS 在第二次点击时为 false
,甚至为什么当此布尔值具有 false
值时它正在运行 setTimeOut()
... ?
我认为在你的代码中 this
in this.allowResendSMS = true
函数的范围(this
的上下文发生变化),而不是周围的 class.
替换
setTimeout(function () {
this.allowResendSMS = true;
console.log('END OF TIMEOUT');
console.log('allowResendSMS: ', this.allowResendSMS)
}, 5000);
和
setTimeout(() => {
this.allowResendSMS = true;
console.log('END OF TIMEOUT');
console.log('allowResendSMS: ', this.allowResendSMS)
}, 5000);
我正在使用 Ionic,Angular 这意味着我正在使用 TypeScript 语言。
我有一个布尔值,如果单击某个元素并且相同的布尔值是 true
,它应该变为 false
。在布尔值变为假后,运行 setTimeOut()
函数,以便在 5000 毫秒后布尔值再次变为 true
。
我面临的问题是运行 setTimeOut()
时。布尔值变为 true
。但是,当我再次单击该元素时(5000 毫秒后),布尔值是 false
...
代码在哪:
resendSMS() {
console.log('allowResendSMS: ', this.allowResendSMS);
if (this.allowResendSMS) {
this.allowResendSMS = false;
console.log('SMS HAS BEEN RESENDED');
console.log('allowResendSMS: ', this.allowResendSMS);
setTimeout(function () {
this.allowResendSMS = true;
console.log('END OF TIMEOUT');
console.log('allowResendSMS: ', this.allowResendSMS)
}, 5000);
}
}
输出在哪里:
(First Click on Element)
allowResendSMS: true
SMS HAS BEEN RESENDED
allowResendSMS: false
END OF TIMEOUT
allowResendSMS: true
(Second Click on Element)
allowResendSMS: false
END OF TIMEOUT
allowResendSMS: true
有人可以提供线索,说明为什么 allowresendSMS 在第二次点击时为 false
,甚至为什么当此布尔值具有 false
值时它正在运行 setTimeOut()
... ?
我认为在你的代码中 this
in this.allowResendSMS = true
函数的范围(this
的上下文发生变化),而不是周围的 class.
替换
setTimeout(function () {
this.allowResendSMS = true;
console.log('END OF TIMEOUT');
console.log('allowResendSMS: ', this.allowResendSMS)
}, 5000);
和
setTimeout(() => {
this.allowResendSMS = true;
console.log('END OF TIMEOUT');
console.log('allowResendSMS: ', this.allowResendSMS)
}, 5000);