How to delay the .keyup() handler until the user stops typing?

前端 未结 27 2600
半阙折子戏
半阙折子戏 2020-11-21 23:32

I’ve got a search field. Right now it searches for every keyup. So if someone types “Windows”, it will make a search with AJAX for every keyup: “W”, “Wi”, “Win”, “Wind”, “Wi

27条回答
  •  忘了有多久
    2020-11-21 23:57

    Based on the answer of CMS, it just ignores the key events that doesn't change value.

    var delay = (function(){
        var timer = 0;
        return function(callback, ms){
          clearTimeout (timer);
          timer = setTimeout(callback, ms);
        };
    })(); 
    
    var duplicateFilter=(function(){
      var lastContent;
      return function(content,callback){
        content=$.trim(content);
        if(content!=lastContent){
          callback(content);
        }
        lastContent=content;
      };
    })();
    
    $("#some-input").on("keyup",function(ev){
    
      var self=this;
      delay(function(){
        duplicateFilter($(self).val(),function(c){
            //do sth...
            console.log(c);
        });
      }, 1000 );
    
    
    })
    

提交回复
热议问题