Skip to content

Instantly share code, notes, and snippets.

@arodbits
Created Sep 3, 2018
Embed
What would you like to do?
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