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';
    @NgModule({
    declarations: [
    AppComponent
    ],
    imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule
    ],
    providers: [
    APP_PROVIDERS,
    [SimpleTimer],
    appRoutingProviders,
    { 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.

testtimer.component.ts

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

  @Component({

selector:'testtimer',
templateUrl:'./testtimer.component.html'
})

export class TestTimer {

   counter1 = 0;
  maxcount =10;

  timer1Id: string;

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

constructor(private st:SimpleTimer) {

}

ngOnInit() {

this.st.newTimer('1sec', 1);

this.timer1Id=this.st.subscribe('1sec', () =>this.timer1callback());

}

timer1callback():void {

this.counter1++;

if(this.counter1===maxcount)

{

this.timer1Img='../../assets/img/timeUp.jpg';

this.st.delTimer('1sec'); }
  }

}

testtimer.component.html

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

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

CONCLUSION

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

w

Connecting to %s