0

Is there a case where setInterval() or interval() is better? Or do they function the exact same? In an online/video course I am taking to increase my knowledge in Angular the guy said to use setInterval for one part, however, I couldn't figure out the syntax to use so I ended up using interval() with .subscribe() and .unsubscribe instead (code below).

It functioned exactly how I wanted to, however I still cannot find if using interval with .subscribe is better or worse. I saw that using .setInterval() in some cases is detrimental but couldn't find much of anything on interval(). If someone could give me some insight into the differences (if any) that would be great!

export class GameControlComponent implements OnInit {

  @Output() numbers = new EventEmitter<{number : number}>();
  //not sure what type to declare here
  num;
  subscription : Subscription;

  constructor() { }

  ngOnInit(): void {

  }

  //event (holding a incrementing number) should get emitted each second (ref = setInterval())
  startCount() {
    this.num = interval(1000);
    this.subscription = this.num.subscribe(n =>
      this.numbers.emit(n));
    console.log(this.num);
  }

  stopCount() {
    this.subscription.unsubscribe();
  }
}
Madeirey
  • 152
  • 2
  • 11
  • What do you mean by `.setInterval()` ? You should have a question marked question in your question. please have a look to the How to ask help page https://stackoverflow.com/help/how-to-ask – ibenjelloun Dec 04 '20 at 15:54
  • I should have a question marked question in my question? Not sure what you mean because I clearly ask a question with a question mark in the title and it's literally the first sentence. Also .setInterval() is a function which is a built in Javascript function so I'm not sure what you want me to say by asking "what do you mean by setInterval()".... https://www.w3schools.com/jsref/met_win_setinterval.asp – Madeirey Dec 04 '20 at 16:04
  • 1
    I actually prefer your reactive approach (interval) over a setInterval! – MikeOne Dec 04 '20 at 17:50
  • 1
    Does this answer your question? [Why would I use RxJS interval() or timer() polling instead of window.setInterval()?](https://stackoverflow.com/questions/52018881/why-would-i-use-rxjs-interval-or-timer-polling-instead-of-window-setinterval) – Krenom Dec 05 '20 at 14:10
  • 1
    @MikeOne Thank you, Mike, that gives me confidence lol! – Madeirey Dec 07 '20 at 14:37
  • 1
    And yes, that helps a lot @Krenom thank you! – Madeirey Dec 07 '20 at 14:37

0 Answers0