Add class every second but only for 5 seconds. [JavaScript]

  class, html, javascript, setinterval, settimeout

I have a problem. 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 with turning on the lights? That is, the lights go out and only then the counting starts.

Source: Ask Javascript Questions

LEAVE A COMMENT