Skip to content

Instantly share code, notes, and snippets.

@arodbits
Created September 3, 2018 04:26
Show Gist options
  • Save arodbits/ec14024149bd5c900303e27514c0cf1b to your computer and use it in GitHub Desktop.
Save arodbits/ec14024149bd5c900303e27514c0cf1b to your computer and use it in GitHub Desktop.
a traffic light system
let states = {
'red': {'nextSlot':'green', 'await':10000, 'exec':function(element){
element.className = 'red'
setTimeout(function(){
element.className = ''
states.green.exec(document.getElementById(states.red.nextSlot))
}, states.red.await)
}},
'green': {'nextSlot':'yellow','await':10000, 'exec':function(element){
element.className = 'green'
setTimeout(function(){
element.className = ''
states.yellow.exec(document.getElementById(states.green.nextSlot))
}, states.green.await)
}},
'yellow': {'nextSlot':'red', 'await':5000, 'exec':function(element){
element.className = 'yellow'
let intervalId = setInterval(function(){
if(states.yellow.await == 0){
element.className = ''
states.red.exec(document.getElementById(states.yellow.nextSlot))
clearInterval(intervalId)
}else{
element.className = element.className == 'yellow' ? '' : 'yellow'
states.yellow.await -= 1000
}
}, 1000)
}}
}
let element = document.getElementById('red')
states['red'].exec(element)
// html
<div id="green"></div>
<div id="yellow"></div>
<div id="red"></div>
//css
.green{
background: green;
}
.red{
background: red;
}
.yellow{
background: yellow;
}
#green, #yellow, #red {
width:20px;
height: 20px;
border: 1px solid black;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment