0

I use the following method changing a property after a certain amount of time:

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

It works, but sometime this approach seems to be unreliable in terms of flickering, jumping etc.

Is there another, better way to achieve a similar behavior?

Tom
  • 3,672
  • 6
  • 20
  • 52
  • `interval` is indeed an alternative to `setInterval`, does that suffice? It sounds like you might still run into a flicker issue. – Jason Awbrey Nov 19 '19 at 06:48
  • @JasonAwbrey Kind of. If I leave the tab for a while and come back, it sometimes seems to be sped up - is there a way to prevent that? – Tom Nov 20 '19 at 18:40
  • As far as this question is concerned for SO, i'd agree that the RxJS `interval` is a sufficient alternative to `setInterval`. I think to dig into the other issues you're experiencing they would fit better into a new question with some more code examples. If you open that up feel free to ping me in a comment on there. – Jason Awbrey Nov 22 '19 at 18:21

2 Answers2

7

You can use interval.

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

Note that I changed the field name in the assignment from interval to intervalSubscription so it is not confused with the import interval (there is no naming collision, it is strictly for read-ability).

Igor
  • 60,821
  • 10
  • 100
  • 175
  • Thank you, but if I leave the tab for a while and come back, it sometimes kind of seems to be sped up - is there a way to prevent that? – Tom Nov 20 '19 at 18:39
  • Clear the interval when you leave the page, in a `ngOnDestroy` or some similar method then re-declare the interval on returning to that page that has helped me in the past when facing a similar issue. @Tim – Dylan Anlezark Dec 13 '19 at 03:06
1

You can use an Timer Observable from rxjs, taken from this answer:

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}}
Beshoy Hanna
  • 611
  • 2
  • 9
  • 29