jquery writing time

3

I have a question and I have not been able to find a solution.

What happens is that I'm using a bar code in a input , but this input also has a function to look up real-time data (ajax) in the database, which I try to do when the bar code type and it's very fast, my search function does not skip.

I need something that detects the writing time, if it is very fast just write but if it is slow look.

Thank you very much greetings.

$(document).ready(
    function() {
      //al momento de escribir busca productos
      $("#buscar").keyup(function() {
        mostrarproductos();
      });

    }

    function mostrarproductos() {
      var buscartx = $('#buscar').val();
      $.ajax({
        url: BASE_URL + "vender/mostrarproductos",
        type: "POST",
        data: {
          buscar: buscartx
        },
        success: function(respuesta) {
          var registro = eval(respuesta);
          var contar = 0;
          var html;
          for (var i = 0; i < registro.length; i++) {
            html += "<tr>";
            html += "<td id=" + registro[i]["codigo2"] + ">" + registro[i]["codigo2"] + "</td>";
            html += "<td>" + registro[i]["nombre"] + "</td>";
            html += "<td>" + registro[i]["stock"] + "</td>";
            html += "<td>" + registro[i]["precio"] + "</td>";
            html += "</tr>";
            contar += 1;
          };;
          if (contar > 0) {
            $("#tbody-01").html(html);
            // $("#resultx").text("Resultado encontrados: " + contar);
          } else {
            $("#table-01 tbody tr").remove();
            // $("#resultx").text("Resultado encontrados: 0");
          }
        }
      });
    }
<input id="buscar" name="buscar" 
  class="form-control text-uppercase mx-1 texbox_min"
  type="text" placeholder="Buscar">
    
asked by Daniel P. 24.08.2018 в 15:04
source

1 answer

3

What you could do is put a time counter when you write and when you keep typing, this counter will restart. Only at the end of the time would the call be made.

$(document).ready(function(){
  var tiempoescritura;
    // iniciamos el timer
    $("#buscar").keyup(function(e) {
        clearTimeout(tiempoescritura);
        if (e.keyCode == 13){ // Si se presiona enter no se ejecutará la función
          return true;
        }
        // he puesto 1s, podrías poner el valor que quieras
        tiempoescritura = setTimeout(mostrarproductos, 1000);
    });
    // borramos el timer
    $("#buscar").keydown(function() {
        clearTimeout(tiempoescritura);
    });
    function mostrarproductos(){
      console.log("He dejado de escribir!");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="buscar" name="buscar" class="form-control text-uppercase mx-1 texbox_min" type="text" placeholder="Buscar">

If you run and test you will see the console.log () when you stop typing for 1s.

    
answered by 24.08.2018 / 15:28
source