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

前端 未结 27 2581
半阙折子戏
半阙折子戏 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-22 00:10

    If you want to search after the type is done use a global variable to hold the timeout returned from your setTimout call and cancel it with a clearTimeout if it hasn't yet happend so that it won't fire the timeout except on the last keyup event

    var globalTimeout = null;  
    $('#id').keyup(function(){
      if(globalTimeout != null) clearTimeout(globalTimeout);  
      globalTimeout =setTimeout(SearchFunc,200);  
    }   
    function SearchFunc(){  
      globalTimeout = null;  
      //ajax code
    }
    

    Or with an anonymous function :

    var globalTimeout = null;  
    $('#id').keyup(function() {
      if (globalTimeout != null) {
        clearTimeout(globalTimeout);
      }
      globalTimeout = setTimeout(function() {
        globalTimeout = null;  
    
        //ajax code
    
      }, 200);  
    }   
    

提交回复
热议问题