Skip to content

Instantly share code, notes, and snippets.

@arturcarvalho
Last active January 10, 2022 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arturcarvalho/7eb202646916e4c0f7fe3aacb987d467 to your computer and use it in GitHub Desktop.
Save arturcarvalho/7eb202646916e4c0f7fe3aacb987d467 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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