Pergunta

Como posso atrasar ações entre keypress em jQuery. Por exemplo;

Eu tenho algo parecido com isto

 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();
    }
 });
}

Eu quero impedir que os dados de postagem se o usuário continuamente digitação. Então, como posso dar .5 segundos de atraso?

Foi útil?

Solução

Você pode usar habilidades de dados do jQuery para fazer isso, algo como isto:

$('#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();
    }
  });
}

A principal vantagem aqui é nenhuma variável global em todo o lugar, e você poderia envolver isso em uma função anônima no setTimeout se você queria, apenas tentando fazer o exemplo o mais limpo possível.

Outras dicas

Tudo que você precisa fazer é envolver sua função em um tempo limite que fica redefinida quando o usuário pressiona uma tecla:

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

Em seguida, basta invocar "wrapper" em seu evento chave.

Há um agradável plugins para lidar com isso. jQuery acelerador / Debounce

A resposta de Nick é perfeito, mas ao manusear primeiro evento imediatamente é fundamental, então eu acho que nós podemos fazer:

$(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)
        }
    }
});

Eu envolvê-lo em uma função assim:

  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();
                }
            });
        }
    }


  }

Dessa forma, não importa quantas vezes você ping isso, você nunca vai procurar mais do que a cada 500 milissegundos.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top