【问题标题】:How to stop rxjs timer如何停止 rxjs 计时器
【发布时间】:2019-02-21 23:39:36
【问题描述】:

我有以下计时器:

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();
            }

          })
        );
      }

如何停止计时器?例如。当用户点击按钮时...

【问题讨论】:

    标签: typescript timer rxjs


    【解决方案1】:

    假设您使用的是 angular,如果您只使用 javascript,您可以只使用我们 fromEvent() 来创建 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();
                }
    
              })
            );
          }
    

    【讨论】:

    • 如果计数器被takeUntil中断,我不想执行finalize怎么办
    • 我认为作为第二个问题,结构需要改变
    猜你喜欢
    • 2019-10-04
    • 2021-08-31
    • 1970-01-01
    • 2012-05-05
    • 2014-08-24
    • 1970-01-01
    • 2023-04-11
    • 2012-03-23
    • 2017-05-18
    相关资源
    最近更新 更多