Created
February 21, 2018 10:15
-
-
Save danielkcz/fa2d1e066cf01a942342877e5768dd87 to your computer and use it in GitHub Desktop.
Timing with MST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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