Skip to content

Instantly share code, notes, and snippets.

@JayBee007
Last active September 11, 2021 09:45
Show Gist options
  • Save JayBee007/3b2fcf60bd9bc6985f4f72cd71e6a020 to your computer and use it in GitHub Desktop.
Save JayBee007/3b2fcf60bd9bc6985f4f72cd71e6a020 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const timerMachine = Machine({
id: 'timerMachine',
initial: "paused",
context: {
totalRounds: 2,
roundsLeft: 2,
roundDuration: 15,
intervalDuration: 10,
fightSecondsLeft: 15,
intervalSecondsLeft: 10
},
states: {
paused: {
on: {
START: {
target: 'running.hist'
}
}
},
running: {
initial: 'round',
invoke: {
src: () => (cb) => {
let timerId = setInterval(() => {
cb('TICK')
}, 1000)
return () => clearInterval(timerId)
},
},
states: {
hist: {type: 'history'},
round: {
initial: 'fight',
exit: assign((ctx,evt) => {
if(evt.type === "") {
return ({
roundsLeft: ctx.roundsLeft - 1,
fightSecondsLeft: ctx.roundDuration
})
}
}),
states: {
fight: {
on: {
'': {
target: 'warning',
cond: (ctx) => ctx.fightSecondsLeft < 10
}
}
},
warning: {}
},
on: {
TICK: {
actions: assign({
fightSecondsLeft: (ctx) => ctx.fightSecondsLeft - 1
})
},
'': {
target: 'interval',
cond: (ctx) => ctx.fightSecondsLeft < 0
}
}
},
interval: {
exit: assign((ctx,evt) => {
if(evt.type === "") {
return ({
intervalSecondsLeft: ctx.intervalDuration
})
}
}),
on: {
TICK: {
actions: assign({
intervalSecondsLeft: (ctx) => ctx.intervalSecondsLeft - 1
})
},
'': {
target: 'round',
cond: (ctx) => ctx.intervalSecondsLeft < 0
}
}
}
},
on: {
PAUSED: {
target: 'paused'
},
'': {
target: 'paused',
cond: ctx => ctx.roundsLeft < 1
}
}
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment