jakesgordon / javascript-state-machine

A javascript finite state machine library
MIT License
8.69k stars 964 forks source link

state in progress, and can't do transition. #125

Open sunq0001 opened 7 years ago

sunq0001 commented 7 years ago

i used it by another way, because for me it is easier to understand when function is in state rather than in transition. but the problem comes if i don't use setTimeout, it will show error. "transition is invalid while previous transition is still in progress" but if i add setTimeout(function(){}, 0); error is gone. could you help solve it?

var FSM = StateMachine.factory({
    init: 'start',
    transitions: [
        { name: 'step', from: 'start', to: 'A' },
        { name: 'step', from: 'A', to: 'B' },
        { name: 'step', from: 'B', to: 'C' },
        { name: 'step', from: 'C', to: 'D' },
        { name: 'step', from: 'D', to: 'start' }
    ],

    methods: {
        onStep: function () {
            var self = this;
            var obj = {
                'start': function () {
                    console.log(`i am in ${self.state} state`);
                    **setTimeout(function () {
                        self.step();
                    }, 0);**
                },
                'A': function () {
                    console.log(`i am in ${self.state} state`);
                    **setTimeout(function () {
                        self.step();
                    }, 0);**
                },
                'B': function () {
                    console.log(`i am in ${self.state} state`);
                    **setTimeout(function () {
                        self.step();
                    }, 0);**
                },
                'C': function () {
                    console.log(`i am in ${self.state} state`);
                    **setTimeout(function () {
                        self.step();
                    }, 0);**
                },

                'D': function () {
                    console.log(`i am in ${self.state} state`);
                    **setTimeout(function () {
                        self.step();
                    }, 0);**
                }
            }
            obj[self.state]();
        }
    }

});

var fsm1 = new FSM();  // 'init()' transition fires from 'none' to 'A' for fsm1
fsm1.step();
adami commented 7 years ago

i don't really understand why you used the fsm like that...

i think what happens is:

sunq0001 commented 7 years ago

It is just a demo that shows my questions. my suggestion is that there should be some function that can force state transition although it is still in progress. and i think this is quite common situtation. the state is interrupted by some action and have to transit immediately.

BTW: Below is game which used state-machine, and i have to use setTimout(fn, 0) to dismiss the error message. https://github.com/sunq0001/Tetris