The gentleman, a RxJs timer which wait for process to finish executed before next interval

Viewed 320

I want a timer/interval that run every x ms, and I will run some processes during the intervals.

What I need? I want the timer to wait for my process to finished before triggering next interval, how?

I am doing animation, so it is ok if some of the intervals are slightly longer. Just want to make sure all processes are finish executed.

enter image description here

3 Answers

So you want the delay to be at least xms but always wait until the process completes:

const getProcess = () => {
  console.log('creating process...');
  return timer(500 + Math.random() * 1000); // mock process
};

const source = forkJoin(
  timer(1000),
  defer(() => getProcess())
).pipe(
  repeat(),
);

source.subscribe(() => console.log('sub'));

Live demo: https://stackblitz.com/edit/rxjs-jhvorc

timer() will emit just once and complete and forkJoin() will guarantee that both source Observables complete before it emits. Then repeat() will subscribe to its source again and repeat the whole process.

I think the forkJoin() suggestion by @martin seems overly complicated. This is a simpler version, which does not trigger the same action immediately after it executed slowly:

const checkSessionTimer = defer(() => this.checkSession()).pipe(
  delay(3*1000),
  repeat()
);

checkSessionTimer.subscribe()
Related