【问题标题】:TypeScript - SetTimeOut bug on variable assign [duplicate]TypeScript-变量分配上的SetTimeOut错误[重复]
【发布时间】: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


【解决方案1】:

我认为在您的代码中,this.allowResendSMS = true 中的 this 作用于函数(this 的上下文发生变化),而不是周围的类。

替换

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);

【讨论】:

  • 非常感谢您的时间和回答!您的解决方案有效!
猜你喜欢
  • 2023-04-08
  • 2016-10-09
  • 1970-01-01
  • 2018-10-02
  • 2015-11-19
  • 2016-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多