2

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?

  • did you try timer from [RXJS](https://www.learnrxjs.io/learn-rxjs/operators/creation/timer) ? – ggr Nov 06 '20 at 07:10
  • I tried it using https://www.npmjs.com/package/ng2-simple-timer but it is not working correclty. I don't know much about RxJs –  Nov 06 '20 at 07:12
  • RxJS is at the heart of Angular for at lot on functionalities (like http calls). So you dont need to import it from npm. Look at the timer function, it will do everything you want – ggr Nov 06 '20 at 07:16
  • how can I do that any example? –  Nov 06 '20 at 07:25
  • you can check this [post](https://stackoverflow.com/questions/34921555/how-to-make-countdown-timer-with-rxjs-observables) – ggr Nov 06 '20 at 07:41

1 Answers1

1

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

Abolfazl Roshanzamir
  • 12,730
  • 5
  • 63
  • 79