Skip to content

Instantly share code, notes, and snippets.

@SandroMaglione
Created May 13, 2025 10:11
Show Gist options
  • Save SandroMaglione/eaed8580e105ac851fcd62a20797f67a to your computer and use it in GitHub Desktop.
Save SandroMaglione/eaed8580e105ac851fcd62a20797f67a to your computer and use it in GitHub Desktop.
Actor logic for a timer implemented using `xstate` ⏱️
import { assign, fromCallback, setup } from "xstate";
type TickEvent = { type: "tick" };
const timerLogic = fromCallback(({ sendBack }) => {
const timer = setInterval(() => {
sendBack({ type: "tick" } satisfies TickEvent);
}, 1000);
return () => {
clearInterval(timer);
};
});
const machine = setup({
types: {
context: {} as { time: number },
events: {} as TickEvent,
children: {} as { timer: "timer" },
},
actors: { timer: timerLogic },
}).createMachine({
context: { time: 0 },
invoke: { src: "timer", id: "timer" },
on: {
tick: {
actions: assign(({ context }) => ({
time: context.time + 1,
})),
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment