timers in angular application

Viewed 163

I am working on an angular application. I want to use a timer in my application such that when I call that timer and pass a dynamic value of time it should show a pop up after that.

For example if I start a timer and pass 60secs to it, it should show me a pop up after 60secs. I have code of my pop up just don't know how to implement a timer giving dynamic time at runtime. Also I need to delete timer in case if I get response from backend in those 60secs or what ever the dynamic value I pass for timer. How can I do that?

1 Answers

You can use rxjs timer . first of all import timer form rxjs

import { Subscription, timer } from 'rxjs'

then in your component :

  public timer: Subscription;

  ngOnInit() {

  }

  showPopupAfterSpecificTime(time = 10000) {
    const numbers = timer(time);
    this.timer = numbers.subscribe(x => this.openPopup());
  }

  private openPopup() {
    console.log("Now You Can Open Your Modal")
  }

  ngOnDestroy(): void {
    if (this.timer) this.timer.unsubscribe()
  }

the default value for showPopupAfterSpecificTime is 10 seconds you can pass your time

In your HTML : Here I pass 5 seconds

<button type="button" (click)="showPopupAfterSpecificTime(5000)">
  open Popup
</button>

NOTE:

to prevent memory leak you have to unsubscribe in ngOnDestroy

Stackblitz Here

Related