Pregunta

¿Cómo puedo retrasar Me acciones entre pulsación de tecla en jQuery. Por ejemplo;

Tengo algo como esto

 if($(this).val().length > 1){
   $.post("stuff.php", {nStr: "" + $(this).val() + ""}, function(data){
    if(data.length > 0) {
      $('#suggestions').show();
      $('#autoSuggestionsList').html(data);
    }else{
      $('#suggestions').hide();
    }
 });
}

Quiero evitar la publicación de datos si el usuario de forma continua a escribir. Entonces, ¿cómo puedo dar retardo .5 segundos?

¿Fue útil?

Solución

Puede utilizar las capacidades de datos de jQuery para hacer esto, algo como esto:

$('#mySearch').keyup(function() {
  clearTimeout($.data(this, 'timer'));
  var wait = setTimeout(search, 500);
  $(this).data('timer', wait);
});

function search() {
  $.post("stuff.php", {nStr: "" + $('#mySearch').val() + ""}, function(data){
    if(data.length > 0) {
      $('#suggestions').show();
      $('#autoSuggestionsList').html(data);
    }else{
      $('#suggestions').hide();
    }
  });
}

La ventaja principal aquí hay variables globales por todo el lugar, y usted podría terminar con esto de una función anónima en el setTimeout si quería, tratando de hacer el ejemplo lo más limpio posible.

Otros consejos

Todo lo que necesita hacer es envolver su función en un tiempo de espera que se pone a cero cuando el usuario presiona una tecla:

var ref;
var myfunc = function(){
   ref = null;
   //your code goes here
};
var wrapper = function(){
    window.clearTimeout(ref);
    ref = window.setTimeout(myfunc, 500);
}

A continuación, simplemente invocar el "contenedor" en su evento clave.

Hay un buen plugin para manejar esto. jQuery acelerador / de rebote

La respuesta de Nick es perfecto pero si el manejo primer evento inmediato es crítico entonces creo que podemos hacer:

$(selector).keyup(function(e){ //or another event

    if($(this).val().length > 1){
        if !($.data(this, 'bouncing-locked')) {

            $.data(this, 'bouncing-locked', true)

            $.post("stuff.php", {nStr: "" + $(this).val() + ""}, function(data){
                if(data.length > 0) {
                    $('#suggestions').show();
                    $('#autoSuggestionsList').html(data);
                }else{
                    $('#suggestions').hide();
                }
           });

            self = this
            setTimeout(function() {
                $.data(self, 'bouncing-locked', false);

                //in case the last event matters, be sure not to miss it
                $(this).trigger("keyup"); // call again the source event
            }, 500)
        }
    }
});

Me envuelvo en una función de este modo:

  var needsDelay = false;

  function getSuggestions(var search)
  {
    if(!needsDelay)
    {
        needsDelay = true;
        setTimeout("needsDelay = false", 500);

        if($(this).val().length > 1){
            $.post("stuff.php", {nStr: "" + search + ""}, function(data){
                if(data.length > 0) {
                    $('#suggestions').show();
                    $('#autoSuggestionsList').html(data);
                }else{
                    $('#suggestions').hide();
                }
            });
        }
    }


  }

De esa manera, no importa cuántas veces se hace ping esto, nunca buscará más de cada 500 milisegundos.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top