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>

            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");
            let timer= setInterval(timerSet,1500);

            function timerSet(){


else if("yellow"){"green";"black";"black";

else if ("green"){"red";"black";




            function Kreis(element,radius,farbe){





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.

let timer= null;
function startTimer(){
    timer = setInterval(timerSet,1500);

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

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

function stopTimer(){
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 .