首页 > 解决方案 > rxjs 定期或定时器到期时调用函数

问题描述

我需要在函数完成后每 5000 毫秒调用一次函数。我怎么能做到这一点。

即使函数需要更长的时间,我当前的实现也会每 5000 毫秒调用一次

const { BehaviorSubject, timer} = require("rxjs");


const subject = new BehaviorSubject(false)

async function doit() {
    console.log('hey')
    subject.next(true)
}

timer(0, 5000).subscribe(() => {
    doit()
})

标签: rxjs

解决方案


使用exhaustMap,在doit完成之前不会占用新项目。确保它返回可观察的

timer(0, 5000).pipe(
   exhaustMap(_ => doit())
).subscribe();

推荐阅读