Skip to content

Commit

Permalink
emitting an event when status of timer changes (#2)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
jbbpatel94 authored and mathiasvr committed Nov 27, 2018
1 parent d233d4b commit 960c22a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```

Expand Down Expand Up @@ -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`
Expand Down
13 changes: 9 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down

0 comments on commit 960c22a

Please sign in to comment.