My simple way:
function Timer (callback, delay) {
let callbackStartTime
let remaining = 0
this.timerId = null
this.paused = false
this.pause = () => {
this.clear()
remaining -= Date.now() - callbackStartTime
this.paused = true
}
this.resume = () => {
window.setTimeout(this.setTimeout.bind(this), remaining)
this.paused = false
}
this.setTimeout = () => {
this.clear()
this.timerId = window.setInterval(() => {
callbackStartTime = Date.now()
callback()
}, delay)
}
this.clear = () => {
window.clearInterval(this.timerId)
}
this.setTimeout()
}
How to use:
let seconds = 0_x000D_
const timer = new Timer(() => {_x000D_
seconds++_x000D_
_x000D_
console.log('seconds', seconds)_x000D_
_x000D_
if (seconds === 8) {_x000D_
timer.clear()_x000D_
_x000D_
alert('Game over!')_x000D_
}_x000D_
}, 1000)_x000D_
_x000D_
timer.pause()_x000D_
console.log('isPaused: ', timer.paused)_x000D_
_x000D_
setTimeout(() => {_x000D_
timer.resume()_x000D_
console.log('isPaused: ', timer.paused)_x000D_
}, 2500)_x000D_
_x000D_
_x000D_
function Timer (callback, delay) {_x000D_
let callbackStartTime_x000D_
let remaining = 0_x000D_
_x000D_
this.timerId = null_x000D_
this.paused = false_x000D_
_x000D_
this.pause = () => {_x000D_
this.clear()_x000D_
remaining -= Date.now() - callbackStartTime_x000D_
this.paused = true_x000D_
}_x000D_
this.resume = () => {_x000D_
window.setTimeout(this.setTimeout.bind(this), remaining)_x000D_
this.paused = false_x000D_
}_x000D_
this.setTimeout = () => {_x000D_
this.clear()_x000D_
this.timerId = window.setInterval(() => {_x000D_
callbackStartTime = Date.now()_x000D_
callback()_x000D_
}, delay)_x000D_
}_x000D_
this.clear = () => {_x000D_
window.clearInterval(this.timerId)_x000D_
}_x000D_
_x000D_
this.setTimeout()_x000D_
}
_x000D_
The code is written quickly and did not refactored, raise the rating of my answer if you want me to improve the code and give ES2015 version (classes).