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

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

    jQuery:

    var timeout = null;
    $('#input').keyup(function() {
      clearTimeout(timeout);
      timeout = setTimeout(() => {
          console.log($(this).val());
      }, 1000);
    });
    
    

    Pure Javascript:

    let input = document.getElementById('input');
    let timeout = null;
    
    input.addEventListener('keyup', function (e) {
        clearTimeout(timeout);
        timeout = setTimeout(function () {
            console.log('Value:', input.value);
        }, 1000);
    });

提交回复
热议问题