Set timer for trafic light in Javascript

I want to set a timer with two Button for my trafic Light. One button for start. another one for stop.

I want that when ever user clicked on start button then Trafic light start to working and change his color, and when ever user clicked stop then Trafic light also stop working. I have a code which is working just Automaticly and not with button. ( circles automaticly change his color even when user not click on any button)

How can i set the buttons for that duty ?

<button id="btn1">start</button>
<button id="btn2">stop</button>
    <div id="div1"></div>
        <div id="div2"></div>
        <div id="div3"></div>


        <script>
           
            const btn1=document.getElementById("btn1");
            const btn2=document.getElementById("btn2");
            const div1=document.getElementById("div1");
            const div2=document.getElementById("div2");
            const div3=document.getElementById("div3");
            
            
            btn1.addEventListener("click",timerSet)
            let timer= setInterval(timerSet,1500);
            

            function timerSet(){

    if(div1.style.backgroundColor=="red"){

    div2.style.backgroundColor="yellow";
    div1.style.backgroundColor="black";
    div3.style.backgroundColor="black";



}
else if(div2.style.backgroundColor=="yellow"){
    div3.style.backgroundColor="green";
    div2.style.backgroundColor="black";
    div1.style.backgroundColor="black";

}
else if (div3.style.backgroundColor=="green"){
    div1.style.backgroundColor="red";
    div3.style.backgroundColor="black";
}
                


            }
            

            

            
            Kreis(div1,20,"red");
            Kreis(div2,20,"black");
            Kreis(div3,20,"black");


            function Kreis(element,radius,farbe){

            element.style.backgroundColor=farbe;
            element.style.width=2*radius+"px";
            element.style.height=2*radius+"px";
            element.style.borderRadius=2*radius+"px";

}



            </script>

Answer

You need to move your setInterval statement into your event listener. At the moment you have it in global space meaning it will run right away.

btn1.addEventListener("click",startTimer)
let timer= null;
function startTimer(){
    timer = setInterval(timerSet,1500);
}

function timerSet(){
   /* ... */
}

To stop you just put a clearInterval call in another click listener

btn2.addEventListener('click',stopTimer);
function stopTimer(){
    clearInterval(timer);
}
Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .