Created
April 7, 2020 13:56
-
-
Save davidkpiano/78fef4bd3ae520709ceaee62c0dd59cd to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains hidden or 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
const ticker = ctx => cb => { | |
const interval = setInterval(() => { | |
cb("TICK"); | |
}, ctx.interval * 1000); | |
return () => clearInterval(interval); | |
}; | |
const timerExpired = (ctx) => ctx.elapsed >= ctx.duration; | |
const createTimerMachine = (duration) => | |
Machine({ | |
id: "timer", | |
initial: "idle", | |
context: { | |
duration, | |
elapsed: 0, | |
interval: 0.1 | |
}, | |
states: { | |
idle: { | |
entry: assign({ | |
duration, | |
elapsed: 0 | |
}), | |
on: { | |
TOGGLE: "running", | |
RESET: undefined | |
} | |
}, | |
running: { | |
invoke: { | |
id: "ticker", // only used for viz | |
src: ticker | |
}, | |
initial: "normal", | |
states: { | |
normal: { | |
on: { | |
"": { | |
target: "overtime", | |
cond: timerExpired | |
}, | |
RESET: undefined | |
} | |
}, | |
overtime: { | |
on: { | |
TOGGLE: undefined | |
} | |
} | |
}, | |
on: { | |
TICK: { | |
actions: assign({ | |
elapsed: ctx => ctx.elapsed + ctx.interval | |
}) | |
}, | |
TOGGLE: "paused", | |
ADD_MINUTE: { | |
actions: assign({ | |
duration: ctx => ctx.duration + 60 | |
}) | |
} | |
} | |
}, | |
paused: { | |
on: { TOGGLE: "running" } | |
} | |
}, | |
on: { | |
RESET: { | |
target: ".idle" | |
} | |
} | |
}); | |
createTimerMachine(60) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment