2

I want to run my code as soon as it gets into my component and repeat the logic every 5 seconds

Here is my code, I used the interval of rxjs

ngOnInit() {
  const ticker = interval(5000);
  ticker.subscribe(() => {
    this.calculateTime();
  });
}

But the issue here is that for the code runs

1st time at 5s 
2nd time at 10s

But I want it to run as

1st time at 0s 
2nd time at 5s
3rs time at 10s

This is how I tacked:

ngOnInit() {
  const ticker = interval(5000);
  this.calculateTime();
  ticker.subscribe(() => {
    this.calculateTime();
  });
}

If you notice I called this.calculateTime(); twice once before ticker and 2nd inside ticker.

Is there a better solution using interval ? If not may be an alternative to interval

Varun Sukheja
  • 6,170
  • 5
  • 51
  • 93
  • 2
    Possible duplicate of [How to get an observable to return data immediately and every 5 seconds thereafter](https://stackoverflow.com/questions/36612945/how-to-get-an-observable-to-return-data-immediately-and-every-5-seconds-thereaft) – Vahid Jan 20 '19 at 15:08

2 Answers2

3

You can use timer. It does the same as interval but adds the functionality you need: controlling the first emission.

ngOnInit() {
  const ticker = timer(0, 5000);
  ticker.subscribe(() => {
    this.calculateTime();
  });
}
a better oliver
  • 26,330
  • 2
  • 58
  • 66
0

Try the following:

import { startWith } from 'rxjs/operators';
// ....
const ticker = interval(5000).pipe(
     startWith(0)
);
Kristian Vitozev
  • 5,791
  • 6
  • 36
  • 56