Reputation: 59
I want to create a function that will add a class every second but after 5 seconds the function will end. This function should add an active class to one of the five lights.
My code at the moment looks like this:
const lights = document.querySelectorAll('.light');
let active = true;
const headFunction = () => {
lightsFunction();
}
const lightsFunction = () => {
if (active) {
for (let i = 0; i < lights.length; i++) {
lights[i].classList.add('on');
}
} else {
for (let i = 0; i < lights.length; i++) {
lights[i].classList.remove('on');
}
}
}
headFunction();
I would also like to ask about one thing. How to make the function with counting time run only after finishing the function by turning on the lights? That is, the lights go out, and only then the counting starts.
Upvotes: 1
Views: 1249
Reputation: 6505
You could use setTimeout with different delays to add and remove the classes.
By adding an if statement you can check if you are done turning all the lights on/off.
const LIGHT_ACTIVE_CLASS = 'light--on';
const ACTIVE_TIME = 1000; // milliseconds
const lights = document.querySelectorAll('.light');
const turnAllLightsOff = (lights) => {
lights.forEach((light) => {
light.classList.remove(LIGHT_ACTIVE_CLASS);
});
}
lights.forEach((light, index) => {
// Turn light on
setTimeout(() => {
light.classList.add(LIGHT_ACTIVE_CLASS);
// Check if it's the last light
if(index === lights.length - 1) {
// Wait a bit before turning the lights off
setTimeout(() => {
// Turn all lights off
turnAllLightsOff(lights);
console.log('Finished...');
}, ACTIVE_TIME);
}
}, index * ACTIVE_TIME);
});
.light {
width: 2rem;
height: 2rem;
background: grey;
display: inline-block;
margin: 0 0.5em 0 0;
}
.light--on {
background: yellow;
box-shadow: 0 0 1rem yellow;
}
<div class="light"></div>
<div class="light"></div>
<div class="light"></div>
<div class="light"></div>
<div class="light"></div>
If you want to show a single light at a time:
const LIGHT_ACTIVE_CLASS = 'light--on';
const ACTIVE_TIME = 1000; // milliseconds
const lights = document.querySelectorAll('.light');
lights.forEach((light, index) => {
// Turn light on
setTimeout(() => {
light.classList.add(LIGHT_ACTIVE_CLASS);
}, index * ACTIVE_TIME);
// Turn light off
setTimeout(() => {
light.classList.remove(LIGHT_ACTIVE_CLASS);
// Check if it's the last light
if(index === lights.length - 1) {
console.log('Finished...');
}
}, (index * ACTIVE_TIME) + ACTIVE_TIME);
});
.light {
width: 2rem;
height: 2rem;
background: grey;
display: inline-block;
margin: 0 0.5em 0 0;
}
.light--on {
background: yellow;
box-shadow: 0 0 1rem yellow;
}
<div class="light"></div>
<div class="light"></div>
<div class="light"></div>
<div class="light"></div>
<div class="light"></div>
Upvotes: 4