Created
April 20, 2022 04:01
-
-
Save deanrad/d134c8a6a8473e186e6e85090a002210 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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
const timerMachine = Machine({ | |
context: { | |
elapsed: 0, | |
duration: 5, | |
interval: 0.01 | |
}, | |
initial: "running", | |
on: { | |
RESET: { | |
target: "running", | |
actions: assign({ | |
elapsed: 0 | |
}) | |
}, | |
DURATION: { | |
actions: assign({ | |
duration: (ctx, event) => event.value | |
}) | |
} | |
}, | |
states: { | |
running: { | |
invoke: { | |
id: "timer", | |
src: (ctx, event) => (sendBack) => { | |
console.log("starting interval"); | |
const i = setInterval(() => { | |
sendBack("TICK"); | |
}, 1000 * ctx.interval); | |
return () => { | |
console.log("clearing interval"); | |
clearInterval(i); | |
}; | |
} | |
}, | |
always: { | |
target: "paused", | |
cond: (ctx) => ctx.elapsed >= ctx.duration | |
}, | |
on: { | |
TICK: { | |
actions: assign({ | |
elapsed: (ctx) => +(ctx.elapsed + ctx.interval).toFixed(2) | |
}) | |
} | |
} | |
}, | |
paused: { | |
always: { | |
// we want to be "running" whenever elapsed > duration | |
target: "running", | |
cond: (ctx) => ctx.elapsed < ctx.duration | |
} | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment