how to count time while writing in an input text?

0

Good, I have this code

var timer =null;
        function interval(){


        if (timer != null)
        {
          clearInterval(timer)
          timer = null
        }

        let elem = document.getElementById("segundos");
        elem.textContent="0s!!!";

        timer = setInterval(function(){

          let elem = document.getElementById("segundos");
          elem.textContent="3s!!!";
          elem.style.color = "red";
         alert('duro mas de 3');
         clearInterval(timer);
          timer = null;
          $('#buscador').val('');
          $('#buscador').html('');
        },3000);

    }


    $('#buscador').on('input',function(){
        interval();
    });

What I want to do is to count the time when a key is pressed, for example if I write in the input: h (it counts for 3 seconds if it takes more than 3 seconds to do something) if it does not exceed 3 seconds then it restarts the account and so on I do not know if I explain myself well, I have no idea how to do it.

I'm ready to update the code, it worked like this

    
asked by Juan Jose 26.12.2018 в 19:11
source

1 answer

1

Here is an example of how you can do it. In this case, each time the user presses a key, the countdown is restarted. Otherwise, if it reaches 0 (zero), it shows a "Lost" message. Greetings!

var control = setInterval(initCount,1000);
var segundos=3;

function initCount(){
 let elem = document.getElementById("segundos");
 segundos = parseInt(elem.textContent);
 segundos = segundos-1;
 elem.textContent=segundos;
 //si se termina el tiempo...
 if(segundos==0){
  // Finalizamos el "juego"
  endGame();
  }
}
function endGame(){
  let elem = document.getElementById("segundos")
  elem.textContent="Perdiste!!!";
  elem.style.color = "red";
  clearInterval(control);
 }
// cada vez que se ingresa un caracter en el input, se reinicia el contador.
function resetCount(){
  document.getElementById("segundos").textContent=3;
}
<textarea oninput="resetCount();"></textarea>
Tiempo restante: <span id="segundos">3</span>
    
answered by 26.12.2018 / 20:51
source