I have a small problem: I have to make two traffic lights, one for Street 1 and one for Street 2 . Bearing in mind that while it is green on Lane 1 , it must be red on Lane 2 and vice versa .
I have a problem with the time intervals, since they start well but then they speed up and almost come together, until the synchronization is lost.
I'll leave you the code with HTML and JavaScript :
function start() {
cambios(1);
cambios(2);
}
function cambios(id) {
var cont = 1;
var bomb1;
bomb1 = document.getElementById("bombillo"+id);
function colorRojo() {
if (cont == 1) {
bomb1.style.background = "red";
cont += 2;
}
}
window.setInterval(colorRojo, 5000);
window.clearInterval(colorRojo);
function colorAmarillo() {
if (cont == 2) {
bomb1.style.background = "yellow";
cont -= 1;
}
}
window.setInterval(colorAmarillo, 5000);
window.clearInterval(colorAmarillo);
function colorVerde() {
if (cont == 3) {
bomb1.style.background = "green";
cont -= 1;
}
}
window.setInterval(colorVerde, 7000);
window.clearInterval(colorVerde);
}
start()
#bombillo1 {
height: 150px;
width: 150px;
background-color: green;
border-radius: 50%;
margin: 25px auto;
transition: background 300ms;
}
#bombillo2 {
height: 150px;
width: 150px;
background-color: red;
border-radius: 50%;
margin: 25px auto;
transition: background 300ms;
}
<!-- jQuery usado como dependencia de Bootstrap -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" >
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
<div class="bombillo" id="bombillo1"></div>
<div class="bombillo" id="bombillo2"></div>
<div class="btn-group"></div>
I recommend you do this via
requestAnimationFrame
as it has many advantages oversetInterval/setTimeout
. Some advantages are better FPS, spend less CPU and battery, among others. Also, if you want synchronization between both semaphores you must implement the Observer pattern (also called pub/sub).Example
The class
Observer
only roughly implements the Observer pattern, defining the methodssubscribe
to subscribe to another semaphore and the methodpublish
to notify "observer" semaphores when a light change has occurred.The class
Semaphore
as you can see has nothing out of the ordinary. The propertybreakpoints
is the "break points" at which the semaphore should change. In this example, green will last 5, red 3, and amber 2.I pass you the script in JQuery:
You just have to add the fnSemaphore function in the ready block , as follows:
I hope it is useful for you! successes!
edit: I add the code in pure JS, in case you need it: