diff --git a/plugins/play/scratch.js b/plugins/play/scratch.js new file mode 100644 index 00000000..d81fbc48 --- /dev/null +++ b/plugins/play/scratch.js @@ -0,0 +1,7 @@ +import spacetime from 'spacetime' +import plugin from './src/index.js' + +spacetime.extend(plugin) + +let s = spacetime.now() +s.play() diff --git a/plugins/play/src/Ticker.js b/plugins/play/src/Ticker.js new file mode 100644 index 00000000..5f8c6b5e --- /dev/null +++ b/plugins/play/src/Ticker.js @@ -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') }) diff --git a/plugins/play/src/index.js b/plugins/play/src/index.js new file mode 100644 index 00000000..20471390 --- /dev/null +++ b/plugins/play/src/index.js @@ -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