Implementing Timer in Angular

In the series of angular blogs to solve some real application problems, I will show how to include a timer or counter in Angular in this blog.

Using ng2-simple-timer

I have implemented this using ng2-simple-timer,  which is a simple service based on RxJS.

Here I will show the steps on how to include this in your application.

  1. Install using npm
    npm install ng2-simple-timer
  2. Import and include as a provider in the AppModule(or the specific module if you have multiple modules in your application), so that it is available as a provider for all components in the module. In this example, I will include in app.module.ts as below
    import { SimpleTimer } from 'ng2-simple-timer';
    declarations: [
    imports: [
    providers: [
    { provide: LocationStrategy, useClass: HashLocationStrategy },
    { provide: APP_BASE_HREF, useValue: '!' }],
    bootstrap: [AppComponent]
    export class AppModule { }
  3. Import and use in your Component in which you want to include the timer. In the below example I have a 1 sec timer which ticks for a given number of seconds and times out. The image changes from ticktock.gif to timeout.jpg when the maxcount is reached. Here I have deleted the timer directly, but you can unsubscribe and subscribe again later if required.


import {SimpleTimer} from 'ng2-simple-timer';



export class TestTimer {

   counter1 = 0;
  maxcount =10;

  timer1Id: string;

   timer1Img = '../../assets/img/ticktock.gif';

constructor(private st:SimpleTimer) {


ngOnInit() {'1sec', 1);'1sec', () =>this.timer1callback());


timer1callback():void {




this.timer1Img='../../assets/img/timeUp.jpg';'1sec'); }



<h2 class="ui center aligned header">Time to test our timer</h2>

< img src="{{timer1Img}}" >


Now you can easily design your own timer in your application using this approach. Don’t forget to unsubscribe and delete the timer when not in use.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s