Forem

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

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)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay