Angular2 Simple Timer Service


A simple timer service for Angular 2, base on RxJS.

Name/ID(string) base API. RxJS object not exposed.



npm install ng2-simple-timer  


Import into Angular 2 RC5 application (typescript)

ng2-simple-timer is implemented as Angular 2 injectable service name SimpleTimer.

For module using SimpleTimer

Add SimpleTimer into module providers (eg. app.module.ts).

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

    providers: [SimpleTimer]

For each child component using SimpleTimer

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

export class ChildComponent {

    constructor(private st: SimpleTimer) { }




newTimer(name: string, sec: number): boolean

newTimer will create timer name and tick every ‘number’ of seconds. Creating timer with the same name multiple times has no side effect.

Return false if timer name exist.'5sec', 5);  

delTimer(name: string): boolean

delTimer will delete timer name

Return false if timer name does not exist.'5sec');  

getTimer(): string[]

getTimer will return all timer name in string array.

let t: string[] =;  

getSubscription(): string[]

getSubscription will return all subscription id in string array.

let ids: string[] =;  

subscribe(name: string, callback: (any) => void): string

subscribe will link callback function to timer name. Whenever timer name tick, callback will be invoked.

Return subscription id(string).

Return empty string if timer name does not exist.

Either use Lambda(fat arrow) in typescript to pass in callback or bind this to another variable in javascript, else this scope will be lost.

Lambda(fat arrow)

counter: number = 0;  
timerId: string;

ngOnInit() {  
    // lazy mode
    this.timerId ='5sec', e => this.callback());

callback() {  

unsubscribe(id: string): boolean

unsubscribe will cancel subscription using id.

unsubscribe will return false if id is undefined or id is not found in subscription list.

timerId: string;;  


GitHub: ng2-simple-timer-example
Plunker: Angular2 Simple Timer Example