Created
September 3, 2018 04:26
-
-
Save arodbits/ec14024149bd5c900303e27514c0cf1b to your computer and use it in GitHub Desktop.
a traffic light system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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