Last active
January 10, 2022 07:25
-
-
Save arturcarvalho/7eb202646916e4c0f7fe3aacb987d467 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 timerMachine = Machine({ | |
initial: 'running', | |
context: { | |
elapsed: 0, | |
duration: 5, | |
interval: 0.1 | |
}, | |
states: { | |
running: { | |
invoke: { | |
src: context => cb => { | |
const interval = setInterval(() => { | |
cb('TICK'); | |
}, 1000 * context.interval); | |
return () => { | |
clearInterval(interval); | |
}; | |
} | |
}, | |
on: { | |
'always': { | |
target: 'stopped', | |
cond: context => { | |
return context.elapsed >= context.duration; | |
} | |
}, | |
TICK: { | |
actions: assign({ | |
elapsed: context => +(context.elapsed + context.interval).toFixed(2) | |
}) | |
} | |
} | |
}, | |
stopped: { | |
on: { | |
'always': { | |
target: 'running', | |
cond: context => context.elapsed < context.duration | |
} | |
} | |
} | |
}, | |
on: { | |
'DURATION.UPDATE': { | |
actions: assign({ | |
duration: (_, event) => event.value | |
}) | |
}, | |
RESTART: { | |
actions: assign({ | |
elapsed: 0 | |
}) | |
} | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment