Skip to content

Commit

Permalink
start timer plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
spencermountain committed Dec 27, 2023
1 parent b728cd6 commit 84a4b61
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
7 changes: 7 additions & 0 deletions plugins/play/scratch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import spacetime from 'spacetime'
import plugin from './src/index.js'

spacetime.extend(plugin)

let s = spacetime.now()
s.play()
36 changes: 36 additions & 0 deletions plugins/play/src/Ticker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/* global performance */

// recursive setTimeOut - not perfect, but does not drift
// https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript
// see benchmarks at https://github.com/dbkaplun/driftless
class Ticker {
constructor(hertz, callback) {
this.target = performance.now() // target time for the next frame
this.interval = (1 / hertz) * 1000 // the milliseconds between ticks
this.callback = callback
this.stopped = false
this.frame = 0
this.tick(this)
}

tick(self) {
if (self.stopped) {
return
}
const currentTime = performance.now()
const currentTarget = self.target
const currentInterval = (self.target += self.interval) - currentTime

setTimeout(self.tick, currentInterval, self)
self.callback(self.frame++, currentTime, currentTarget, self)
}

stop() {
this.stopped = true
return this.frame
}
}

export default Ticker

// let c = new Ticker(2, () => { console.log('tick') })
21 changes: 21 additions & 0 deletions plugins/play/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
let methods = {
start: function () {
this.startEpoch = this.epoch
return this
},
stop: function () {
this.startEpoch = null
this.isRunning = false
return this
},
pause: function () {
this.isRunning = false
return this
},
elapsed: async function () {
let start = this._from(this.startEpoch, this.tz)
return this.diff(start)
}
}
methods.play = methods.start
export default methods

0 comments on commit 84a4b61

Please sign in to comment.