how do i make this traffic light count properly the duration ("duração"), after the first cicle, starts a visual glitch on the timer glitch
var sinal = setTimeout(red, 0)
function red() {
let i = 0
vermelho.style.backgroundColor = cores[0];
amarelo.style.backgroundColor = cores_off[1];
verde.style.backgroundColor = cores_off[2];
setTimeout(yellow, 60000)
var d1 = setInterval(function duração1() {
i++
cromonometro.innerHTML = `${i}`
}, 1000)
}
function yellow() {
let i = 0
vermelho.style.backgroundColor = cores_off[0];
amarelo.style.backgroundColor = cores[1];
verde.style.backgroundColor = cores_off[2];
setTimeout(green, 7000)
var d2 = setInterval(function duração2() {
i++
cromonometro.innerHTML = `${i}`
}, 1000)
}
function green() {
let i = 0
vermelho.style.backgroundColor = cores_off[0];
amarelo.style.backgroundColor = cores_off[1];
verde.style.backgroundColor = cores[2];
setTimeout(red, 60000)
var d3 = setInterval(function duração3() {
i++
cromonometro.innerHTML = `${i}`
}, 1000)
}
i tried to use clear interval, but i don’t have the knowledge yet
2
Answers
Make
d1
,d2
, andd3
global variables. Then each function can clear the previous interval.BTW, your cycle is backwards. The normal order is green -> yellow -> red.
There is a way of doing this that might be easier to follow. By using async/await you can write a function that ‘sleeps’ for a number of seconds, we can then use that function instead of calling setTimeout and setInterval.
(Unfortunately there is no built in sleep function in JavaScript, but we can create one with a oneliner, basically we create a promise that will resolve after a number of ms that you choose when you call the sleep function. And since await is just one way of calling promises await sleep(milliseconds) then works fine inside an async function.)
We create an array with the sequence and time each light should be on, easy to find and change since it is separate from the rest of the programming logic.
Then we just loop through that array, turn the right light on, sleep for the duration specified in the array and turn the light off, moving on to the next part of the sequence in the next iteration of the loop, and so on…
At the end of our function we call the function again (recursion) to repeat the sequence.