<!DOCTYPE html>
<html>
  <head>
    <title>Angular2 Simple Timer Example</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="https://unpkg.com/core-js/client/shim.min.js"></script>

    <script src="https://unpkg.com/zone.js@0.7.4?main=browser"></script>
    <script src="https://unpkg.com/systemjs@0.19.40/dist/system.src.js"></script>

    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>

  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>
import {Component, OnInit} from '@angular/core';

// Import ng2-simple-timer as SimpleTimer
import {SimpleTimer} from 'ng2-simple-timer';

@Component({
	'selector': 'my-app',
	'template': `
		<p>
		ng2-simple-timer is available in
		  <a href="https://www.npmjs.com/package/ng2-simple-timer">npm</a> and 
      <a href="https://github.com/J-Siu/ng2-simple-timer">github</a>.
    This example is available in
      <a href="https://github.com/J-Siu/ng2-simple-timer-example">github</a>.
    </p>
		<div style="border: 1px solid;margin:5px;padding:5px">
  		<h3>{{title}}</h3>
  		<div><button (click)="subscribeTimer0()">{{timer0button}}  1 sec timer0</button>{{counter0}}</div>
  		<div><button (click)="subscribeTimer1()">{{timer1button}}  5 sec timer1</button>{{counter1}}</div>
  		<div><button (click)="subscribeTimer2()">{{timer2button}} 10 sec timer2</button>{{counter2}}</div>
  		<div style="border: 1px solid;margin:5px;padding:5px">
    		Timer can no longer be subscribed or unscubscribed once deleted.
    		<div><button (click)="delAllTimer()">Delete all timer</button></div>
      </div>
    </div>`
})
export class AppComponent implements OnInit {
	title = 'Angular2 Simple Timer Service Example';

	counter0 = 0;
	timer0Id: string;
	timer0button = 'Subscribe';

	counter1 = 0;
	timer1Id: string;
	timer1button = 'Subscribe';

	counter2 = 0;
	timer2Id: string;
	timer2button = 'Subscribe';

	// Define SimpleTimer as 'st'
	constructor(private st: SimpleTimer) { }

	ngOnInit() {
		this.st.newTimer('1sec',1);
		this.st.newTimer('5sec',5);
		this.st.newTimer('10sec',10);
		this.subscribeTimer0();
		this.subscribeTimer1();
		this.subscribeTimer2();
	}

	delAllTimer() {
		this.st.delTimer('1sec');
		this.st.delTimer('5sec');
		this.st.delTimer('10sec');
	}

	subscribeTimer0() {
		if (this.timer0Id) {
			// Unsubscribe if timer Id is defined
			this.st.unsubscribe(this.timer0Id);
			this.timer0Id = undefined;
			this.timer0button = 'Subscribe';
			console.log('timer 0 Unsubscribed.');
		} else {
			// Subscribe if timer Id is undefined
			this.timer0Id = this.st.subscribe('1sec', e => this.timer0callback());
			this.timer0button = 'Unsubscribe';
			console.log('timer 0 Subscribed.');
		}
		console.log(this.st.getSubscription());
	}

	subscribeTimer1() {
		if (this.timer1Id) {
			// Unsubscribe if timer Id is defined
			this.st.unsubscribe(this.timer1Id);
			this.timer1Id = undefined;
			this.timer1button = 'Subscribe';
			console.log('timer 1 Unsubscribed.');
		} else {
			// Subscribe if timer Id is undefined
			this.timer1Id = this.st.subscribe('5sec', e => this.timer1callback());
			this.timer1button = 'Unsubscribe';
			console.log('timer 1 Subscribed.');
		}
		console.log(this.st.getSubscription());
	}

	subscribeTimer2() {
		if (this.timer2Id) {
			// Unsubscribe if timer Id is defined
			this.st.unsubscribe(this.timer2Id);
			this.timer2Id = undefined;
			this.timer2button = 'Subscribe';
			console.log('timer 2 Unsubscribed.');
		} else {
			// Subscribe if timer Id is undefined
			this.timer2Id = this.st.subscribe('10sec', e => this.timer2callback());
			this.timer2button = 'Unsubscribe';
			console.log('timer 2 Subscribed.');
		}
		console.log(this.st.getSubscription());
	}

	timer0callback() {
		this.counter0++;
	}

	timer1callback() {
		this.counter1++;
	}

	timer2callback() {
		this.counter2++;
	}
}
/**
 * PLUNKER VERSION
 * (based on systemjs.config.js in angular.io)
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function(global) {
  System.config({
    // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
    transpiler: 'typescript',
    typescriptOptions: {
      emitDecoratorMetadata: true
    },
    paths: {
      // paths serve as alias
      'npm:': 'https://unpkg.com/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',

      // other libraries
      'rxjs': 'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
      'ts': 'npm:plugin-typescript@4.0.10/lib/plugin.js',
      'typescript': 'npm:typescript@2.0.2/lib/typescript.js',

      'angular2-uuid': 'https://npmcdn.com/angular2-uuid/index.js',
      'ng2-simple-timer': 'https://npmcdn.com/ng2-simple-timer/index.js'

    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      '.': {
        defaultExtension: 'ts'
      },
      app: {
        main: './main.ts',
        defaultExtension: 'ts'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

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

import { AppComponent } from './app.component';

@NgModule({
	imports: [
		BrowserModule
	],
	declarations: [
		AppComponent
	],
	providers: [
		SimpleTimer
	],
	bootstrap: [
		AppComponent
	]
})
export class AppModule { }

platformBrowserDynamic().bootstrapModule(AppModule);
# ng2-simple-timer

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

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

## Index

- [Install](#install)
- [Usage](#usage)
	- ["noImplicitAny": false](#noimplicitany-false)
	- [Import into Angular 2 RC5 application (typescript)](#import-into-angular-2-rc5-application-typescript)
	- [API](#api)
		- [newTimer](#newtimername-string-sec-number-boolean)
		- [delTimer](#deltimername-string-boolean)
		- [getTimer](#gettimer-string)
		- [getSubscription](#getsubscription-string)
		- [subscribe](#subscribename-string-callback-any-void-string)
		- [unsubscribe](#unsubscribeid-string-boolean)
- [Example](#example)
- [Contributors](#contributors)
- [Changelog](#changelog)
- [License](#license)

## Install

```
npm install ng2-simple-timer
```

## Usage

### "noImplicitAny": false

Must set `"noImplicitAny": false` in application __tsconfig.json__. Else following error may occure at build time:

    error TS7006: Parameter 'any' implicitly has an 'any' type

### Import into Angular2 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](https://github.com/J-Siu/ng2-simple-timer-example/blob/master/app/app.module.ts)).

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

@NgModule({
	providers: [SimpleTimer]
})
```

__For each child component using SimpleTimer__

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

export class ChildComponent {

	constructor(private st: SimpleTimer) { }

}
```

### API

##### newTimer

`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.

```javascript
this.st.newTimer('5sec', 5);
```

##### delTimer

`delTimer(name: string): boolean`

`delTimer` will delete timer `name`

Return `false` if timer `name` does not exist.

```javascript
this.st.delTimer('5sec');
```

##### getTimer

`getTimer(): string[]`

`getTimer` will return all timer name in string array.
```javascript
let t: string[] = this.st.getTimer();
```

##### getSubscription

`getSubscription(): string[]`

`getSubscription` will return all subscription id in string array.
```javascript
let ids: string[] = this.st.getSubscription();
```

##### subscribe

`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)__
```javascript
counter: number = 0;
timerId: string;

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

callback() {
	this.counter++;
}
```

##### unsubscribe

`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.

```javascript
timerId: string;

this.st.unsubscribe(this.timerId);
```

## Example

GitHub: [ng2-simple-timer-example](https://github.com/J-Siu/ng2-simple-timer-example)
Plunker: [Angular2 Simple Timer Example](http://embed.plnkr.co/HaTd8q/)

## Contributors

* [John Sing Dao Siu](https://github.com/J-Siu)


## Changelog

* 0.2.0
	- Angular 2 RC4
* 0.2.2
	- API change
		- newTimer() return boolean
		- subscribe() - lazy mode removed
	- API new
		- delTimer()
* 0.2.3
	- Support Angular 2 RC5
* 0.2.4
	- Remove module, export `SimpleTimer` only
* 1.2.4
	- Support Angular 2.0.0
	- Clean up package
* 1.2.5
	- Add Plunker example
* 1.2.7
	- Support Angular 2.4.*
	- Replace node-uuid with uuid
* 1.2.8
	- Change uuid as dependency
* 1.2.9
	- Replace uuid with angular2-uuid
* 1.3.0
	- Add instruction for `"noImplicitAny": false`
	- Clean up package

## License

The MIT License

Copyright (c) 2016

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.