Traffic-Light-Animation
Working animation with non-blocking setTimeout
HTML
<div class="traffic-light">
<button class="request-go"></button>
<div class="light stop active"></div>
<div class="light prepare"></div>
<div class="light go"></div>
</div>
CSS
* {
box-sizing: border-box;
}
body {
zoom: 0.6;
}
.traffic-light {
background-color: black;
width: 320px;
padding: 10px;
}
.light {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: grey;
margin-top: 10px;
}
.stop.active {
background-color: red;
}
.prepare.active {
background-color: yellow;
}
.go.active {
background-color: green;
}
.request-go {
width: 40px;
height: 40px;
border-radius: 50%;
background-color: orange;
border: 5px solid grey;
margin-bottom: 20px;
margin-left: 30px;
}
JavaScript
function prepare(){
document.querySelector('.prepare').classList.add('active');
}
function go(){
document.querySelector('.stop').classList.remove('active');
document.querySelector('.prepare').classList.remove('active');
document.querySelector('.go').classList.add('active');
}
function stop(){
document.querySelector('.go').classList.remove('active');
document.querySelector('.stop').classList.add('active');
}
document.addEventListener('DOMContentLoaded', function(){
document.querySelector('.request-go').addEventListener('click',function(){
setTimeout( function(){
prepare();
setTimeout( function(){
go();
setTimeout( function(){
stop();
}, 2000);
}, 500);
}, 1000 );
}, false);
});