delaying actions between keypress in jQuery

后端 未结 5 1233
刺人心
刺人心 2020-12-08 02:23

How can I delay actions between keypress in jQuery. For example;

I have something like this

 if($(this).val().length > 1){
   $.post(\"stuff.php\"         


        
5条回答
  •  轮回少年
    2020-12-08 03:10

    I'd wrap it in a function like so:

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

    That way no matter how many times you ping this, you will never search more than every 500 milliseconds.

提交回复
热议问题