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

前端 未结 27 2625
半阙折子戏
半阙折子戏 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:02

    Delay function to call up on every keyup. jQuery 1.7.1 or up required

    jQuery.fn.keyupDelay = function( cb, delay ){
      if(delay == null){
        delay = 400;
      }
      var timer = 0;
      return $(this).on('keyup',function(){
        clearTimeout(timer);
        timer = setTimeout( cb , delay );
      });
    }
    

    Usage: $('#searchBox').keyupDelay( cb );

提交回复
热议问题