我正在构建一个 RxJS 幻灯片,如果用户按住右箭头键,我想每隔 500 毫秒导航到下一个图 block 。我正在使用 throttleTime
,如下所示:
const forwardNavigation$ = fromEvent(document, 'keydown').pipe(
filter(event => event.keyCode === KEY_CODE.arrowRight),
throttleTime(500)
);
我现在想做的是在我导航到第 5 个图 block 而不松开箭头键后将 throttleTime 减少到 100ms。
这可能吗?如何实现?
最佳答案
如果您想要一种仅使用 Observables 的更具声明性的方法,以下方法也适用:
const source$ = fromEvent(document, 'keydown').pipe(
filter((event: KeyboardEvent) => event.code === "ArrowRight")
);
const slow$ = source$.pipe(throttleTime(500), take(5));
const fast$ = source$.pipe(throttleTime(100));
const forwardNavigation$ = concat(slow$, fast$);
// subscribe to forwardNavigation$ and execute navigation code
它所做的是从键盘事件创建两个具有不同 throttleTimes 的 Observable。然后它使用 concat
合并两者的结果,这将忽略第二个直到第一个完成。将 take(5)
添加到第一个 observable 意味着它在 5 次发射后完成,此时 fast$
Observable 接管。
工作 StackBlitz .
关于javascript - RxJS:在 X 排放后更改 throttleTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57967740/