用js打造一个格式化的计时器(00:00:00)
function Timer (time, type) {
this.init(time, type)
}
Timer.prototype.init = function (time, type) {
this.time = time || 0
if (type === undefined) {
this.type = true
} else {
this.type = type
}
}
Timer.prototype.start = function () {
this.reTime()
}
Timer.prototype.reTime = function () {
if (this.type) {
this.time++
} else if (this.time > 0) {
this.time--
} else {
this.outputTime('00:00:00')
return
}
let h = parseInt(this.time/3600)
let m = parseInt((this.time - h*3600) / 60)
let s = this.time - h*3600 - m*60
h < 10 ? h = `0${h}` : ''
m < 10 ? m = `0${m}` : ''
s < 10 ? s = `0${s}` : ''
this.outputTime(`${h}:${m}:${s}`)
setTimeout(this.reTime.bind(this), 1000)
}
Timer.prototype.outputTime = function (str) {
console.log(str)
}