Skip to content

Instantly share code, notes, and snippets.

@deanrad
Created April 20, 2022 04:01
Show Gist options
  • Save deanrad/d134c8a6a8473e186e6e85090a002210 to your computer and use it in GitHub Desktop.
Save deanrad/d134c8a6a8473e186e6e85090a002210 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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