@dn-l/timer-state-machine

Simple self-transitioning state machine implementation. Automatically changes state when the lifetime of a current state is over.

Usage no npm install needed!

<script type="module">
  import dnLTimerStateMachine from 'https://cdn.skypack.dev/@dn-l/timer-state-machine';
</script>

README

timer-state-machine

npm npm version

Simple self-transitioning state machine implementation. Automatically changes state when the lifetime of a current state is over.

diagram

Usage

Create a timerStateMachine instance:

const timerStateMachine = new TimerStateMachine([
  {
    name: "study",
    duration: 2700000, // 45 minutes in ms
  },
  {
    name: "break",
    duration: 900000, // 15 minutes in ms
  },
]);
timerStateMachine.start();

Start with the first state:

timerStateMachine.start();

Or resume with any state if you want to continue:

timerStateMachine.start({
  name: "break",
  duration: 540000, // 9 minutes left
});

Subscribe to state changed event:

const onStateChanged = (newState) => {
  console.log(newState);
};
const unsubscribe = timerStateMachine.subscribe(onStateChanged);

Unubscribe specified subscription:

unsubscribe();

// or

timerStateMachine.unsubscribe(onStateChanged);

Unubscribe all subscriptions:

timerStateMachine.unsubscribe();