eonarheim / TypeState

A strongly typed finite state machine for TypeScript
http://eonarheim.github.io/TypeState/example/
BSD 2-Clause "Simplified" License
272 stars 29 forks source link

State Machine Timeout #29

Open stefnotch opened 5 years ago

stefnotch commented 5 years ago

Timeouts are reasonably common in state machines, however manually implementing them requires quite a number of lines of code. It might be nice if this library had built-in support for them.

Maybe something along the lines of:

public stateTimeout<U extends keyof T>(state: U, to: keyof T, timeout: number) {
         this.on(state, (from, context) => {
            (<any>context).timeout = setTimeout(() => {
              this.go(to);
            }, timeout);
          });

          this.onExit(state, (from, context) => {
            if ((<any>context).timeout) {
              clearTimeout((<any>context).timeout);
              (<any>context).timeout = 0;
            }
            return true;
          });
      }