Angular 6 setTimeout 和clearTimeout 错误

Angular 6 setTimeout and clearTimeout error

我有一个 angular 6 奇怪的问题。

我正在使用 setTimeout 和 clearTimeout 函数来 start/cancel 超时。 然而,这有时有效,有时无效。 即使用户触发(点击)事件并且 clearTimeout 为 运行,有时它也会强制玩家抓两张牌。

这是代码

//an event that says we must call uno 
this._hubService.mustCallUno.subscribe(() => {
      this.mustCallUno = true;
      this._interval = window.setInterval(() => {
        this.countdown -= 100;
      }, 100);
      this._timer = window.setTimeout(() => {
        if (this.mustCallUno) {
            this.drawCard(2);
            this.callUno();
        }
      }, 2000);
    });

// a function player calls from UI to call uno and not draw 2 cards
  callUno() {
    this.mustCallUno = false;
    window.clearTimeout(this._timer);
    window.clearInterval(this._interval);
    this.countdown = 2000;
  }

所以即使玩家调用callUno()函数,setTimeout也会被执行。更糟糕的是,代码通过 setTimeout if( this.mustCallUno) 中的第一个 if 检查,这无论如何应该是假的,因为我们只是在调用 callUno() 函数时将它设置为假 this.mustCallUno = false;.

我在window.setTimeout之前用了setTimeout(returnsNodeJS.Timer),结果还是一样

检查 this._hubService.mustCallUno.subscribe 中的函数是否有可能 运行 两次或多次,通常最初是您可能没有预料到的。将记录器放入传递给 mustCallUno.subscribecallUno.

的函数中

在这种情况下,可能发生的情况是 this._timerthis._interval 将具有不同的引用,而它们持有的旧引用未被清除,因为 callUno 未被调用或被调用调用次数少于订阅中的回调。

您使用的是angular6+,所以我建议您使用反应式编程库,例如rxjs

我给你做了个小例子here