setTimeout and clearTimeout giving error

2

I'm having problems with this Script, initially its purpose is to just show the controls while the mouse moves or clicks on the div, and when it stops moving it hides the controls after a while, it works normally, but after a few more uses it starts to bugar and I do not know how to solve it, I am using it to hide the controls of a player, below I made a small example of how I am using it, if someone could help me, I would be grateful!

function inicializacao() {
  player = document.getElementById("player");
  controles = player.querySelector(".controles");
  player.addEventListener("mousemove", controle, false);
  player.addEventListener("mousedown", controle, false);
  player.addEventListener("keydown", controle, false);
}
window.onload = inicializacao;

function controle(event) {
  var tempoContado = setTimeout(Off, 3000);
  On();

  function On() {
    controles.style.bottom = "0px";
    clearTimeout(tempoContado);
    tempoContado = setTimeout(Off, 3000);
  }

  function Off() {
    controles.style.bottom = "-50px";
  }
}
#player,
#player * {
  padding: 0px;
  margin: 0px;
}

#player {
  background: yellow;
  position: relative!important;
  height: 50px;
  width: 400px;
}

.controles {
  background: red;
  position: absolute;
  height: 50px;
  width: 100%;
  bottom: 0;
  left: 0;
}
<div id="player">
  <div class="controles"></div>
</div>
    
asked by anonymous 09.05.2018 / 02:41

1 answer

0

In the way you are doing, setTimeout is running several times when one of the events you created has occurred, causing one to hit the other.

The best way is to package everything in the window.onload function and set the timer out of the controle() function. See:

window.onload = function(){

   function inicializacao() {
      player = document.getElementById("player");
      controles = player.querySelector(".controles");
      player.addEventListener("mousemove", controle, false);
      player.addEventListener("mousedown", controle, false);
      player.addEventListener("keydown", controle, false);
   }

   inicializacao();

   var tempoContado;
   function controle(event) {
      On();

      function On() {
         controles.style.bottom = "0px";
         clearTimeout(tempoContado);
         tempoContado = setTimeout(Off, 3000);
      }

      function Off() {
         controles.style.bottom = "-50px";
      }
   }
}
#player,
#player * {
  padding: 0px;
  margin: 0px;
}

#player {
  background: yellow;
  position: relative !important;
  height: 50px;
  width: 400px;
  overflow: hidden;
}

.controles {
  background: red;
  position: absolute;
  height: 50px;
  width: 100%;
  bottom: 0;
  left: 0;
}
<div id="player">
   player
  <div class="controles">controles</div>
</div>
  

I added overflow: hidden; to #player so that div .controle disappears.

    
09.05.2018 / 04:29