Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rxjs

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

like image 884
Boo Yan Jiong Avatar asked Dec 06 '25 07:12

Boo Yan Jiong


1 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.

like image 138
martin Avatar answered Dec 09 '25 20:12

martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!