Menu
Basic State Machines

A State Machine is a program, logic circuit, or mechanical device, that has a finite number of legal states. For example a traffic control signal can be in the state of red, yellow, or green. It can't be in the state red and green because that might cause a disaster. It can't be in the state of violet because nobody would know what that means.

Sometimes a state machine is called a finite state machine. It's possible to have an infinite state machine, but that doesn't have many practical uses. A state machine begins from a start state, it then transitions from one legal state to another legal state. You can view a state as a set of specific set of input and output conditions. An action is a change that causes the state machine to transition to another legal state.

Which state the state machine to transition to depends not only upon the current action, but also on what its past states were. So which state an action causes a transition to depends no only on the current state, but on the past state or past states. To accomplish this, a state machine has finite amount of internal memory.

A state machine can be represented with a special kind of flow chart called a state diagram. On a state diagram, each state is represented by a circle, and each transition is represented by an arrow. Sometimes the circles contain labels like "state 1, state 2, state 3, ..." or "S1, S2, S3, ...". Transition arrows can be labeled with letters like "A, B, C, ..." Then a separate table or chart specifies each state and transition.

Traffic control signal state machine

A very common, very simple, example of a state machine is a traffic control signal. The legal states are red, yellow, and green. When red it transitions directly to green. When green, it must transition to yellow before it can transition to red. Shown below is JavaScript code for the traffic control signal state machine.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">

<style>
#lite
{
width:24px;
height:58px;
padding:4px;
border-style: solid;
}
#redbulb
{
border-style: solid;
background-color:red;
}
#yellowbulb
{
border-style: solid;
background-color:#650000;
}
#greenbulb
{
border-style: solid;
background-color:#650000;
}
</style>

<script>
var myTimer;
var lastColor ="off";
var currentColor = "off";

function myState()
{
   switch(lastColor + "|" + currentColor)
   {
       case "off|off":
           document.getElementById("redbulb").style.backgroundColor = "red";
           currentColor = "red";
           break;

      case "off|red":
           lastColor ="red";
           document.getElementById("redbulb").style.backgroundColor = "#650000";
           currentColor = "green";
           document.getElementById("greenbulb").style.backgroundColor = "green";
           break;

     case "red|green":
           lastColor ="green";
           document.getElementById("greenbulb").style.backgroundColor = "#650000";
           currentColor = "yellow";
           document.getElementById("yellowbulb").style.backgroundColor = "yellow";
           break;

     case "green|yellow":
           lastColor ="yellow";
           document.getElementById("yellowbulb").style.backgroundColor = "#650000";
           currentColor = "red";
           document.getElementById("redbulb").style.backgroundColor = "red";
           break;

     case "yellow|red":
           lastColor ="red";
           document.getElementById("redbulb").style.backgroundColor = "#650000";
           currentColor = "green";
           document.getElementById("greenbulb").style.backgroundColor = "green";
           break;
   }
   myTimer = setTimeout(myState, 3000);
}

window.onload = myState;

</script>

</head>
</body>

<div id="lite">
<span id="redbulb">    </span>
<span id="yellowbulb">    </span>
<span id="greenbulb">    </span>
</div>

</body>
</html>

As you know, to use this code you simply have to cut and paste it into a text file (Windows Notepad), save it with the file extension .htm, and then load it into your web browser.

Vending machine state machine

Another very common, very simple, example of a state machine is a vending machine. In the state diagram shown above you can see that a soda costs 25 cents, and to keep it simple, the machine accepts only nickels and dimes, and it does not give change.

The machine starts with no money. Each state is defined by the coins that have been previously deposited into the machine, and the state that it transitions to is determined by the current coin being deposited. Eventually coins totaling 25 cents will have been deposited and a soda will be dispensed, after which the machine transitions back to its starting point. Shown below is JavaScript code for the soda vending machine state machine.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">

<script>
var total = 0;

function myState(currentCoin)
{
   switch(total + "|" + currentCoin)
   {
       case "0|nickel":
           total = 5;
           document.getElementById("total").value = total;
           document.getElementById("vend").value = "";
           break;

      case "0|dime":
           total = 10;
           document.getElementById("total").value = total;
           document.getElementById("vend").value = "";
           break;

     case "5|nickel":
           total += 5;
           document.getElementById("total").value = total;
           document.getElementById("vend").value = "";
           break;

     case "5|dime":
           total += 10;
           document.getElementById("total").value = total;
           document.getElementById("vend").value = "";
           break;

     case "10|nickel":
           total += 5;
           document.getElementById("total").value = total;
           document.getElementById("vend").value = "";
           break;

     case "10|dime":
           total += 10;
           document.getElementById("total").value = total;
           document.getElementById("vend").value = "";
           break;

     case "15|nickel":
           total += 5;
           document.getElementById("total").value = total;
           document.getElementById("vend").value = "";
           break;

     case "15|dime":
           total = 0;
           document.getElementById("total").value = total;
           document.getElementById("vend").value = "Dispense Soda";
           break;

     case "20|nickel":
           total = 0;
           document.getElementById("total").value = total;
           document.getElementById("vend").value = "Dispense Soda";
           break;

     case "20|dime":
           total = 0;
           document.getElementById("total").value = total;
           document.getElementById("vend").value = "Dispense Soda";
           break;
   }

}

</script>

</head>
<body>

<form action="javascript:void(0);">
   <button type="button" onclick="myState('nickel')">Nickel</button>
   <button type="button" onclick="myState('dime')">Dime</button>
   Total:<input type="text" id="total" value="0">
   Vend:<input type="text" id="vend">
</form>

</body>

Most of you will recognize that using a double expression switch statement is overkill for this application. This is for heuristic purposes. The first expression in each branch represents a past state and the second expression represents a condition that triggers a transition to another state. A multiple expression switch statement is a great way to make this apparent.


Learn more at amazon.com

More Java Script Code:
• Code to Drag and Drop an Image Anywhere on a Webpage
• Creating Java Script Dynamic or anonymous Functions at Runtime
• Java Script Code to Calculate Speed / Distance of Falling Object
• Code to Block the Ad Blockers
• Web Site Menus : Which Section Am I In?
• Java Script Message Boxes
• JavaScript Code to Make Image Wave Like a Flag
• Regular Expression Basics : How many Matches?
• JavaScript 24-Hour Trainer
• HTML5 and Local Storage