setInterval()的角度替代

时间:2019-11-18 19:14:38

标签: angular typescript

我使用以下方法在一定时间后更改属性:

switchColors() {
    this.interval = setInterval( () => {
      some code;
    }, 700);
}

它可以工作,但是有时这种方法在闪烁,跳跃等方面似乎并不可靠。

还有另一种更好的方法来实现类似的行为吗?

2 个答案:

答案 0 :(得分:6)

您可以使用interval

import {interval} from 'rxjs';
switchColors() {
    this.intervalSubscription = interval(700).subscribe(() => {
      some code;
    });
}

请注意,我将赋值中的字段名称从interval更改为intervalSubscription,因此它与导入interval不会混淆(没有命名冲突,严格来说是只读的)能力)。

答案 1 :(得分:1)

您可以使用来自this answer的rxjs中的Timer Observable:

import { timer } from 'rxjs';

oberserableTimer() {
    const source = timer(1000, 2000);
    const abc = source.subscribe(val => {
      console.log(val, '-');
      this.subscribeTimer = this.timeLeft - val;
    });
  }

<p (click)="oberserableTimer()">Start Observable timer</p> {{subscribeTimer}}