Start a function in the click and stop it by clicking again?

Asked

Viewed 67 times

1

Initially the background of the circle should be white. When you click the circle run in loop the changeCor function and when you click again leave the background of the white circle stopping the changeCor function. How to do this?

//the circle moves with the keys a, w, s, d, but I cannot execute the above events.

follows the full code:

//----VARIÁVEIS----//
var dx;
var dy;
var px;
var py;
var vel;
var anima;
var ang;
var jog;
var skin;
var rotacao;
var tecla;
var tmp;
var tmpCor;
//-----------------//

function inicia(){
   dx = 0;
   dy = 0;
   px = 0;
   py = 0;
   vel = 5;
   ang = 0;
   rotacao = false;
   estadoCor = false;

   jog = document.getElementById("jog");
   skin = document.getElementById("skin");

   skin.addEventListener("click",giraPara);
   skin.addEventListener("click",mudaCor);
   document.addEventListener("keydown",teclaDw);
   document.addEventListener("keyup",teclaUp);

   tmp = setInterval(enterFrame,5);

   tmpCor = setInterval(mudaCor,1000);

}

//---FUNÇÕES DE ROTAÇÃO DO JOG---//

function gira(){
    if(ang>360){
         ang = 0;
    }
    ang+=8;
    jog.style.transform="rotate("+ang+"deg)";
    anima = requestAnimationFrame(gira);
}

function giraPara(){
   if(!rotacao){
      rotacao = true;
      anima = requestAnimationFrame(gira);
   }else if(rotacao){
      rotacao = false;
      cancelAnimationFrame(anima);
   }

}

//-------------------------------//

//---FUNÇÕES DE MOVIMENTO DO JOG---//

//Teclas --> a=65, w=87, d=68, s=83

function teclaDw(){
   tecla = event.keyCode;


   if(tecla==65){
      dx = -1;
   }else if(tecla==87){
      dy = -1;
   }else if(tecla==68){
      dx = 1;
   }else if(tecla==83){
      dy = 1;
   }
}

function teclaUp(){
   tecla = event.keyCode;

   if(tecla==65){
      dx = 0;
   }else if(tecla==87){
      dy = 0;
   }else if(tecla==68){
      dx = 0;
   }else if(tecla==83){
      dy = 0;
   }
}

function enterFrame(){
   px+= (dx*vel);
   py+= (dy*vel);

   jog.style.left = px + "px";
   jog.style.top = py + "px";
}

//----------------------------------//

//---FUNÇÃO DE CORES---//

function mudaCor(){
   var r = Math.floor(Math.random()*255);
   var g = Math.floor(Math.random()*255);
   var b = Math.floor(Math.random()*255);

   skin.style.backgroundColor= "rgb("+r+","+g+","+b+")";
}

window.addEventListener("load",inicia);
#jog{
     width: 100px;
     height: 100px;
     border: 1px solid #000;
     position: absolute;
     top: 0px;
     left: 0px;
     background-color: #f00;
     display: flex;
}

#skin{
     width: 100px;
     height: 100px;
     border: 2px solid #000;
     background-color: #fff;
     border-radius: 50%;
     margin-left: -1px;
     margin-top: -2px;
     align-self: auto;
     cursor: pointer;
}
<div id="jog">
    <div id="skin"></div>
</div>

1 answer

1


You have to cancel the setInterval tmpCor clicking (see comment in code). You use clearInterval() for that reason:

clearInterval(tmpCor);

Now the tmpCor = setInterval(mudaCor,1000); should be started within the function giraPara() when the variable rotacao for false and canceled when it is true:

function giraPara(){
    if(!rotacao){
       // inicia o temporizador
       tmpCor = setInterval(mudaCor,1000);
        rotacao = true;
        anima = requestAnimationFrame(gira);
    }else if(rotacao){
       // cancela o temporizador
      clearInterval(tmpCor);
        rotacao = false;
        cancelAnimationFrame(anima);
    }

}

And to return to the white background (rgb(255, 255, 255)), check whether the variable rotacao is true or false making a ternary in this line within the function mudaCor():

skin.style.backgroundColor= rotacao ?
    "rgb("+r+","+g+","+b+")" : "rgb(255, 255, 255)";
                 ↑                        ↑
           cor aleatória                branco

That’s because by canceling the setInterval, the timer is not canceled immediately, it will still call the function one last time within the time it has.

Then it would look like this:

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <meta charset="UTF-8">
        <title> Title </title>
        <style>
            #jog{
                width: 100px;
                height: 100px;
                border: 1px solid #000;
                position: absolute;
                top: 0px;
                left: 0px;
                background-color: #f00;
                display: flex;
            }

            #skin{
                width: 100px;
                height: 100px;
                border: 2px solid #000;
                background-color: #fff;
                border-radius: 50%;
                margin-left: -1px;
                margin-top: -2px;
                align-self: auto;
                cursor: pointer;
            }

        </style>

        <script type="text/javascript">
            //----VARIÁVEIS----//
            var dx;
            var dy;
            var px;
            var py;
            var vel;
            var anima;
            var ang;
            var jog;
            var skin;
            var rotacao;
            var tecla;
            var tmp;
            var tmpCor;
            //-----------------//

            function inicia(){
                dx = 0;
                dy = 0;
                px = 0;
                py = 0;
                vel = 5;
                ang = 0;
                rotacao = false;
                estadoCor = false;

                jog = document.getElementById("jog");
                skin = document.getElementById("skin");

                skin.addEventListener("click",giraPara);
                skin.addEventListener("click",mudaCor);
                document.addEventListener("keydown",teclaDw);
                document.addEventListener("keyup",teclaUp);

                tmp = setInterval(enterFrame,5);

            }

            //---FUNÇÕES DE ROTAÇÃO DO JOG---//

            function gira(){
                if(ang>360){
                    ang = 0;
                }
                ang+=8;
                jog.style.transform="rotate("+ang+"deg)";
                anima = requestAnimationFrame(gira);
            }

            function giraPara(){
                if(!rotacao){
                   // inicia o temporizador
                   tmpCor = setInterval(mudaCor,1000);
                    rotacao = true;
                    anima = requestAnimationFrame(gira);
                }else{
                   // cancela o temporizador
                  clearInterval(tmpCor);
                    rotacao = false;
                    cancelAnimationFrame(anima);
                }

            }

            //-------------------------------//

            //---FUNÇÕES DE MOVIMENTO DO JOG---//

             //Teclas --> a=65, w=87, d=68, s=83

            function teclaDw(){
                tecla = event.keyCode;


                if(tecla==65){
                    dx = -1;
                }else if(tecla==87){
                    dy = -1;
                }else if(tecla==68){
                    dx = 1;
                }else if(tecla==83){
                    dy = 1;
                }
            }

            function teclaUp(){
                tecla = event.keyCode;

                if(tecla==65){
                    dx = 0;
                }else if(tecla==87){
                    dy = 0;
                }else if(tecla==68){
                    dx = 0;
                }else if(tecla==83){
                    dy = 0;
                }
            }

            function enterFrame(){
                px+= (dx*vel);
                py+= (dy*vel);

                jog.style.left = px + "px";
                jog.style.top = py + "px";
            }

            //----------------------------------//

            //---FUNÇÃO DE CORES---//

            function mudaCor(){
                    var r = Math.floor(Math.random()*255);
                    var g = Math.floor(Math.random()*255);
                    var b = Math.floor(Math.random()*255);

                     skin.style.backgroundColor= rotacao ? "rgb("+r+","+g+","+b+")" : "rgb(255, 255, 255)";
                }




            window.addEventListener("load",inicia);


        </script>
    </head>

    <body>

        <div id="jog">
            <div id="skin"></div>
        </div>

    </body>
</html>

It is worth noting that the else if in function giraPara() is redundant because if rotacao is not false, can only be true. Just one else:

function giraPara(){
    if(!rotacao){
       // inicia o temporizador
       tmpCor = setInterval(mudaCor,1000);
        rotacao = true;
        anima = requestAnimationFrame(gira);
    }else{
       // cancela o temporizador
      clearInterval(tmpCor);
        rotacao = false;
        cancelAnimationFrame(anima);
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.