DEV Community

ಮಿಥುನ್
ಮಿಥುನ್

Posted on

RxJs interval with condition

We have used setInterval() to run a task multiple times after every specific interval. We need to clear interval after the task is done. Using RxJs interval function we can simulate setInterval function.

import { interval } from "rxjs";

// creating observable
let numbers = interval(1000);

// subscribe function returns reference to observable
let numbesubs = numbers.subscribe(x => {
  console.log("Next: ", x);
  // clearing interval when x reaches 10 value
  if (x == 10) {
    unSubscribingfunction();
  }
});

function unSubscribingfunction() {
    // clearing interval
    numbesubs.unsubscribe();
}

// Logs:
// Next: 0
// Next: 1
// Next: 2
// ..
// Next: 10
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay