[XState] Delay XState Events and Transitions

The passing of time can be represented as an event in XState. Rather than requiring the user to send an event after an amount of time has passed, XState provides the after property.

The value of after is an object whose keys are the milliseconds that should pass before a transition is taken. Consider a stop light transitioning from yellow to red after three seconds:

const { Machine } = require("xstate");

const stopLightMachine = Machine(
  {
    id: "stopLight",
    initial: "red",
    context: {
      rushHourMultiplier: 1
    },
    states: {
      red: {
        after: { RED_TIMER: "yellow" }
      },
      yellow: {
        after: { YELLOW_TIMER: "green" }
      },
      green: {
        after: { GREEN_TIMER: "red" }
      }
    }
  },
  {
    delays: {
      RED_TIMER: context => context.rushHourMultiplier * 4000,
      YELLOW_TIMER: context => context.rushHourMultiplier * 1000,
      GREEN_TIMER: context => context.rushHourMultiplier * 3000
    }
  }
);

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/12220245.html