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

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

    Building upon CMS's answer here's new delay method which preserves 'this' in its usage:

    var delay = (function(){
      var timer = 0;
      return function(callback, ms, that){
        clearTimeout (timer);
        timer = setTimeout(callback.bind(that), ms);
      };
    })();
    

    Usage:

    $('input').keyup(function() {
        delay(function(){
          alert('Time elapsed!');
        }, 1000, this);
    });
    
    0 讨论(0)
  • 2020-11-22 00:22

    From ES6, one can use arrow function syntax as well.

    In this example, the code delays keyup event for 400ms after users finish typeing before calling searchFunc make a query request.

    const searchbar = document.getElementById('searchBar');
    const searchFunc = // any function
    
    // wait ms (milliseconds) after user stops typing to execute func
    const delayKeyUp = (() => {
        let timer = null;
        const delay = (func, ms) => {
            timer ? clearTimeout(timer): null
            timer = setTimeout(func, ms)
        }
        return delay
    })();
    
    searchbar.addEventListener('keyup', (e) => {
        const query = e.target.value;
        delayKeyUp(() => {searchFunc(query)}, 400);
    })
    
    0 讨论(0)
  • 2020-11-22 00:24

    User lodash javascript library and use _.debounce function

    changeName: _.debounce(function (val) {
      console.log(val)                
    }, 1000)
    
    0 讨论(0)
提交回复
热议问题