Angular alternative to setInterval()
我使用以下方法在一定时间后更改属性:
1 2 3 4 5 | switchColors() { this.interval = setInterval( () => { some code; }, 700); } |
它可以工作,但是有时这种方法在闪烁,跳跃等方面似乎并不可靠。
还有另一种更好的方法来实现类似的行为吗?
您可以使用
1 | import {interval} from 'rxjs'; |
1 2 3 4 5 | switchColors() { this.intervalSubscription = interval(700).subscribe(() => { some code; }); } |
请注意,我将赋值中的字段名称从
您可以使用rxjs的Timer Observable,取自以下答案:
1 2 3 4 5 6 7 8 9 10 11 | 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}} |