JSFiddle - React, Tailwind, and code Playground

by ifandelse

HTML

<script src="https://rawgit.com/lodash/lodash/2.4.1/dist/lodash.js"></script>
<script src="https://rawgit.com/ifandelse/machina.js/christmas/lib/machina.js"></script>
<div id="east-west" class="traffic-light stop"></div>
<div id="north-south" class="traffic-light stop"></div>

CSS

.traffic-light {
    border-radius: 50%;
    width: 150px;
    height: 150px;
    border: 1pt solid black;
    margin: 5px;
}

.stop {
    background-color: red;
}

.go {
    background-color: green;
}

.caution {
    background-color: yellow;
}

JavaScript

window.TrafficLight = machina.Fsm.extend({
    initialState: "stop",
	
	states: {
        
        disabled: {
            activate: function(isStopped) {
                this.transition(isStopped ? "stop" : "go");    
            }
        },
	
		stop: {
			advance : "go"
		},
		
		go: {
            _onEnter: function() {
                setTimeout(function() {
                    this.advance();
                }.bind(this), 20000);
            },
			advance : "caution"
		},
		
		caution: {
			_onEnter: function() {
				this.timeout = setTimeout(function() {
					this.handle("advance");
				}.bind(this), 5000);
			},
			
			advance: "stop",
			
			_onExit: function() {
				clearTimeout(this.timeout);
			}
		}
	},
	
    advance: function() {
		this.handle("advance");
	},
    
    activateStopped: function() {
        this.handle("activate", true);
    },
    
    activateStarted:  function() {
        this.handle("activate", false);
    },
});

var app = window.app = {
    eastWest : new TrafficLight(),
    northSouth : new TrafficLight()
};

var eastWest = $("#east-west");
var northSouth = $("#north-south");

app.eastWest.on("transition", function(data) {
    eastWest.removeClass(data.fromState).addClass(data.toState);
});

app.northSouth.on("transition", function(data) {
    northSouth.removeClass(data.fromState).addClass(data.toState);
});

app.eastWest.on("transition", function(data) {
    var newState;
    if(data.fromState === "caution" && data.toState === "stop") {
        setTimeout(function() {
            app.northSouth.advance();
        }, 5000);
    }
});

app.northSouth.on("transition", function(data) {
    var newState;
    if(data.fromState === "caution" && data.toState === "stop") {
        setTimeout(function() {
            app.eastWest.advance();
        }, 5000);
    }
});

app.northSouth.advance();