【问题标题】:How to create pause/resume timer which counts break time also, using RxJS如何使用 RxJS 创建暂停/恢复计时器,它也计算中断时间
【发布时间】:2020-12-13 01:57:30
【问题描述】:

我正在学习 rxjs 并想创建一个带有暂停、恢复和停止选项的计时器。另外,我希望它在我按下暂停按钮后计算休息时间。

我找到了这个例子https://stackblitz.com/edit/typescript-dtnoif?file=index.ts,但对我来说,很难理解我应该把休息计时器放在哪里。谢谢。

【问题讨论】:

标签: rxjs


【解决方案1】:

所以,今天我想出了如何实现这一点,但还有一个错误要修复(计数器在两秒后从 playpause 开始,我还不知道为什么)。

这里是源代码

index.ts

import { interval, fromEvent, merge, empty } from "rxjs";
import { switchMap, mapTo, tap, startWith, scan } from "rxjs/operators";

// elem refs
const remainingLabel = document.getElementById("remaining");
const breakTimerDOM = document.getElementById("break-timer");
const pauseButton = document.getElementById("pause");
const resumeButton = document.getElementById("play");
const stopButton = document.getElementById("stop");

// streams
const resume$ = fromEvent(resumeButton, "click").pipe(
  mapTo({ isCounting: true, isBlocked: false })
);
const pause$ = fromEvent(pauseButton, "click").pipe(
  mapTo({ isCounting: false, isBlocked: false })
);
const stop$ = fromEvent(stopButton, "click").pipe(
  mapTo({ isCounting: false, isBlocked: true, counter: 0, breakCounter: 0 }),
  tap(() => empty())
);

const timer$ = merge(resume$, pause$, stop$).pipe(
  startWith({
    counter: 0,
    breakCounter: 0,
    isCounting: false,
    isBlocked: true
  }),
  scan((state, curr) => ({ ...state, ...curr })),
  switchMap(state => {
    return !state.isBlocked
      ? interval(1000).pipe(
          tap(() => {
            const { isCounting, counter, breakCounter } = state;
            if (isCounting) {
              remainingLabel.innerHTML = counter.toString();
              state.breakCounter = 0;
              state.counter++;
            } else {
              breakTimerDOM.innerHTML = breakCounter.toString();
              state.breakCounter++;
            }
          })
        )
      : empty();
  })
);

timer$.subscribe();

index.html

<h4>
    Time remaining: <span id="remaining">0</span>
</h4>
<h4>
    Break timer: <span id="break-timer">0</span>
</h4>
<button id="pause">
Pause
</button>
<button id="play">
Play
</button>
<button id="stop">
Stop
</button>

你可以从这里https://stackblitz.com/edit/typescript-7z6hab?file=index.ts fork 源代码。

【讨论】:

    猜你喜欢
    • 2017-04-11
    • 2021-12-31
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多