From 960c22af3d21e320e7951a0827bf92d2dc8ab70c Mon Sep 17 00:00:00 2001 From: Jaisa Ram Date: Wed, 28 Nov 2018 03:07:24 +0530 Subject: [PATCH] emitting an event when status of timer changes (#2) * Update index.js * Update README.md emitting an event when status of timer changes * Update index.js updated as per suggestions * Update README.md updated as per suggestion --- README.md | 5 ++++- src/index.js | 13 +++++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 2990c2c..46e0f5b 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ let timer = new Timer() timer.on('tick', (ms) => console.log('tick', ms)) timer.on('done', () => console.log('done!')) - +timer.on('statusChanged', (status) => console.log('status:', status)) timer.start(5000) // run for 5 seconds ``` @@ -52,6 +52,9 @@ Event emitted every `interval` with the current time in ms. ### `timer.on('done', () => {})` Event emitted when the timer reaches the `duration` set by calling `timer.start()`. +### `timer.on('statusChanged', (status) => {})` +Event emitted when the timer status changes. + ## properties ### `timer.time` diff --git a/src/index.js b/src/index.js index ad7eda3..b833661 100644 --- a/src/index.js +++ b/src/index.js @@ -28,27 +28,32 @@ class Timer extends EventEmitter { if (duration == null) throw new TypeError('must provide duration parameter') this._duration = duration this._endTime = Date.now() + duration - this._status = 'running' + this._changeStatus('running') this.emit('tick', this._stopwatch ? 0 : this._duration) this._timeoutID = setInterval(tick.bind(this), interval || this._interval) } stop () { clearInterval(this._timeoutID) - this._status = 'stopped' + this._changeStatus('stopped') } pause () { if (this._status !== 'running') return this._pauseTime = Date.now() - this._status = 'paused' + this._changeStatus('paused') } resume () { if (this._status !== 'paused') return this._endTime += Date.now() - this._pauseTime this._pauseTime = 0 - this._status = 'running' + this._changeStatus('running') + } + + _changeStatus (status) { + this._status = status + this.emit('statusChanged', this._status) } get time () {