【发布时间】:2021-02-06 12:03:41
【问题描述】:
我正在使用 Ionic 和 Angular,这意味着我正在使用 TypeScript 语言。
如果单击某个元素并且相同的布尔值是true,则我有一个应该变为false 的布尔值。在布尔值变为 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引用到类的范围:setTimeout(() => {...}, 5000);。
标签: angular typescript ionic-framework boolean settimeout