Search code examples
typescripttimerrxjs

How to stop rxjs timer


I have the following timer:

setCountDown() {
        let counter = 5;
        let tick = 1000;
        this.countDown = timer(0, tick)
        .pipe(
          take(counter),
          map(() => --counter),
          finalize(() => {
            if (this.currentQuestionNumber < this.questionsToAsk)
              this.showNextQuestion();
            else {
              this.endQuiz();
            }

          })
        );
      }

How can I stop the timer? E.g. when a user clicks on a button...


Solution

  • assuming you are using angular, if you use javascript only you can just us fromEvent() to create userClick

    userClick=new Subject()
    
    click(){userClick.next()}
    
    setCountDown() {
            let counter = 5;
            let tick = 1000;
            this.countDown = timer(0, tick)
            .pipe(
              take(counter),
              map(() => --counter),
              takeUntil(userClick),
              finalize(() => {
                if (this.currentQuestionNumber < this.questionsToAsk)
                  this.showNextQuestion();
                else {
                  this.endQuiz();
                }
    
              })
            );
          }