Created
July 15, 2016 07:55
-
-
Save nowri/4b50f051f484acef3251fe9c076cba6b to your computer and use it in GitHub Desktop.
ES6Timer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const STATE_READY = 1; | |
const STATE_PLAYING = 2; | |
const STATE_PAUSE = 3; | |
const STATE_END = 0; | |
class Timer { | |
constructor(updateFunc, sec) { | |
this.sec = sec; | |
this.updateFunc = updateFunc; | |
this.state = STATE_READY; | |
} | |
start() { | |
this.date = Date.now(); | |
this._run(); | |
this.state = STATE_PLAYING; | |
} | |
_run() { | |
const ms = Date.now() - this.date; | |
const nokori = this.sec*1000 - ms; | |
if(nokori <= 0) { | |
this.updateFunc(0); | |
this.destroy(); | |
} else | |
if(!this.isPause && this.updateFunc){ | |
this.updateFunc(nokori); | |
setTimeout(this._run.bind(this), 33); | |
} | |
} | |
add(sec) { | |
this.date = this.date + (sec * 1000); | |
} | |
pause() { | |
this.state = STATE_PAUSE; | |
this.isPause = true; | |
this.pauseData = Date.now(); | |
} | |
resume() { | |
this.isPause = false; | |
this.date = this.date + (Date.now() - this.pauseData); | |
this.state = STATE_PLAYING; | |
this._run(); | |
} | |
destroy() { | |
delete this.isPause; | |
delete this.updateFunc; | |
delete this.sec; | |
delete this.date; | |
this.state = STATE_END; | |
} | |
static get STATE_READY() { | |
return STATE_READY; | |
} | |
static get STATE_PLAYING() { | |
return STATE_PLAYING; | |
} | |
static get STATE_PAUSE() { | |
return STATE_PAUSE; | |
} | |
static get STATE_END() { | |
return STATE_END; | |
} | |
} | |
export default Timer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment