Skip to content

Instantly share code, notes, and snippets.

@danielkcz
Created February 21, 2018 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielkcz/fa2d1e066cf01a942342877e5768dd87 to your computer and use it in GitHub Desktop.
Save danielkcz/fa2d1e066cf01a942342877e5768dd87 to your computer and use it in GitHub Desktop.
Timing with MST
import { types } from 'mobx-state-tree'
const SECOND = 1 * 1000
const MINUTE = 60 * SECOND
export const TimingModel = types
.model('Timing', {
bySecond: types.optional(types.number, Infinity),
byMinute: types.optional(types.number, Infinity),
autoStart: false,
})
.actions(self => ({
updateBySecond(now: number) {
if (self.bySecond === Infinity || now - self.bySecond >= SECOND) {
self.bySecond = now
}
},
updateByMinute(now: number) {
if (self.byMinute === Infinity || now - self.byMinute >= MINUTE) {
self.byMinute = now
}
},
}))
.extend(self => {
let timeoutId = -1
let getNow = Date.now
const executeUpdate = () => {
const now = getNow()
self.updateBySecond(now)
self.updateByMinute(now)
timeoutId = window.setTimeout(executeUpdate, SECOND)
}
return {
actions: {
start(timeResolver?: () => number) {
if (timeResolver) {
getNow = timeResolver
}
executeUpdate()
},
stop() {
if (timeoutId >= 0) {
window.clearTimeout(timeoutId)
timeoutId = -1
}
},
},
}
})
.actions(self => ({
afterCreate() {
if (self.autoStart) {
self.start()
}
},
}))
export type TTimingModel = typeof TimingModel.Type
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment