Skip to content

Instantly share code, notes, and snippets.

@sheerun
Last active March 7, 2021 14:46
Show Gist options
  • Save sheerun/00e358e7bdbcd2088573e4b7b921ce67 to your computer and use it in GitHub Desktop.
Save sheerun/00e358e7bdbcd2088573e4b7b921ce67 to your computer and use it in GitHub Desktop.
const { performance } = require('perf_hooks');
let callback = () => {}
const ticker = (cb) => {
callback = cb
return () => {
if (callback === cb) {
callback = () => {}
}
}
}
setInterval(() => callback(performance.now()), 10)
class Timer {
constructor() {
this.started = 0
this.nextTick = 0
this.ticks = 0
this.stop = () => {}
this.callback = () => {}
this.step = (timestamp) => {
if (timestamp >= this.nextTick) {
this.callback(this.ticks)
this.ticks += 1
this.nextTick = this.started + this.ticks * this.tickDuration
}
}
}
start(tempo, callback) {
this.started = performance.now()
this.nextTick = 0
this.tickDuration = 60 * 4000 / 16 / tempo
this.callback = callback
this.stop = ticker(this.step)
}
}
const timer = new Timer()
timer.start(60 / 4, () => console.log('tick: ' + (performance.now() - timer.started)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment