How can I get a Countdown Timer to work in Angular 10

5.2k views Asked by At

I am attempting to create an Angular-Nativescript shared app that executes some function when a timer reaches zero. I would also like the timer to restart/reset when the end value is changed.

In Angular 9, this functionality was working with the angular-countdown-timer package.

However, since upgrading to Angular 10, I can't get past the ModuleWithProviders requiring some generic type issue.

I have also tried using angular8-countdown-timer which works when the end value is set on page load but not afterwards (even though the end value in the component is changing).

I also tried some of the older packages like ngx-countdown-timer but no joy as they general fall foul of the ModuleWithProviders restriction.

I've tried using ModuleWithProviders<any> and ModuleWithProviders<unknown> as I've seen suggested in similar posts but the compiler just laughs in my face.

Any help with any of the above or even a way to contact the authors would be appreciated.

1

There are 1 answers

3
JoSSte On

I am not sure if I understand your question completely, but I just updated my own angular9 project to use a slightly more efficient timer, where I am not importing all of rxjs.

I use several counters on the page and serveral resets.

Essentially when I start a timer I generate a new one, and do work when the interval elapses, and then stop the subscription when the stop button is clicked. In order to do what you want, I would guess you just call the .unsubscribe() function from inside the "do stuff" block.

I hope this helps you, or others coming here looking to time stuff in angular 8-10


import { Subscription, timer } from 'rxjs';

...
  subscription: Subscription;


  startTimer(){
    const source = timer(1000, 2000);
    this.subscription = source.subscribe(val => {
       // do stuff you want when the interval ticks
    }
  }

  stopTimer(){
    this.subscription.unsubscribe();
  }

My inspiration is this article.