Answer the question
In order to leave comments, you need to log in
How can I make it so that the function is activated immediately after the previous one?
I have a "Traffic Light" and I can't figure out how to make the signals turn on not immediately, but in turn.
Here is the code
$(function (){
function red(){
function changeFontRed() // Черный сменяется на Красный
{
$('#red').toggleClass('red-black');
$('#red').toggleClass('red');
}
setTimeout(changeFontRed, 1500 )
}
function yellow(){
function changeFontYellow() // Черный сменяется на Желтый
{
$('#yellow').toggleClass('yellow-black');
$('#yellow').toggleClass('yellow');
}
setTimeout(changeFontYellow, 1500 )
}
function green(){
function changeFontGreen() // Черный сменяется на Зеленый
{
$('#green').toggleClass('green-black');
$('#green').toggleClass('green');
}
setTimeout(changeFontGreen, 1500 )
}
setTimeout(red,0)
setTimeout(yellow,0)
setTimeout(green,0)
});
Answer the question
In order to leave comments, you need to log in
and to make a call of the following function at the end of the previous one is not an option?
and you have 3 identical functions, they can be replaced by one in which the color parameter will be transmitted, by which you will access the element
You need to start the next timer from the callback of the previous
one, something like this:
$(function (){
var toRed = true;
function red(){
function changeFontRed() // Черный сменяется на Красный
{
$('#red').toggleClass('red-black');
$('#red').toggleClass('red');
yellow();
}
setTimeout(changeFontRed, 1500 )
}
function yellow(){
function changeFontYellow() // Черный сменяется на Желтый
{
$('#yellow').toggleClass('yellow-black');
$('#yellow').toggleClass('yellow');
if(toRed) { red(); }
else { green(); }
toRed = !toRed; // для желтого будем менять направление по этой переменной
}
setTimeout(changeFontYellow, 1500 )
}
function green(){
function changeFontGreen() // Черный сменяется на Зеленый
{
$('#green').toggleClass('green-black');
$('#green').toggleClass('green');
yellow();
}
setTimeout(changeFontGreen, 1500 )
}
green(); // сразу зажигаем только 1 из цветов
});
I would do it with a promise:
const makeColor = ({selector, startClass = 'black', endClass, timeOut = 1000, }, i = 0) =>
() => new Promise((resolve) => {
setTimeout(() => {
const node = document.querySelector(selector);
const isEven = i % 2 === 0;
node.classList.remove(isEven ? startClass : endClass);
node.classList.add(isEven ? endClass : startClass);
i++;
resolve();
}, timeOut)
});
const red = makeColor({selector: '.red-item', endClass: 'red'});
const green = makeColor({selector: '.green-item', endClass: 'green'});
const yellow = makeColor({selector: '.yellow-item', endClass: 'yellow'});
red()
.then(green)
.then(yellow);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question