Run javascript function when user finishes typing instead of on key up?

前端 未结 29 2448
我寻月下人不归
我寻月下人不归 2020-11-22 04:03

I want to trigger an ajax request when the user has finished typing in a text box. I don\'t want it to run the function on every time the user types a letter because that wo

29条回答
  •  一整个雨季
    2020-11-22 04:41

    Late answer but I'm adding it because it's 2019 and this is entirely achievable using pretty ES6, no third party libraries, and I find most of the highly rated answers are bulky and weighed down with too many variables.

    Elegant solution taken from this excellent blog post.

    function debounce(callback, wait) {
      let timeout;
      return (...args) => {
          clearTimeout(timeout);
          timeout = setTimeout(function () { callback.apply(this, args) }, wait);
      };
    }
    
    window.addEventListener('keyup', debounce( () => {
        // code you would like to run 1000ms after the keyup event has stopped firing
        // further keyup events reset the timer, as expected
    }, 1000))
    

提交回复
热议问题