Idiomatic jQuery delayed event (only after a short pause in typing)? (aka timewatch/typewatch/keywatch)

后端 未结 3 904
情深已故
情深已故 2020-12-07 11:19

Here is some jQuery for a search box that I expect is actually an antipattern, and am sure there is a much better solution for that I would love to be pointed towards:

相关标签:
3条回答
  • 2020-12-07 12:04

    I frequently use the following approach, a simple function to execute a callback, after the user has stopped typing for a specified amount of time::

    $(selector).keyup(function () {
      typewatch(function () {
        // executed only 500 ms after the last keyup event.
      }, 500);
    });
    

    Implementation:

    var typewatch = (function(){
      var timer = 0;
      return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
      };
    })();
    

    I think this approach is very simple, and it doesn't imply any global variables.

    For more sophisticated usages, give a look to the jQuery TypeWatch Plugin.

    0 讨论(0)
  • 2020-12-07 12:09

    Have a look at the excellent Text Change Event plugin from Zurb, purveyors of the highest quality jQuery goods.

    0 讨论(0)
  • 2020-12-07 12:10

    This is a more good way to do it, without using the plugin:

    var timeout;
    $('input[type=text]').keypress(function() {
    if(timeout) {
        clearTimeout(timeout);
        timeout = null;
    }
    
    timeout = setTimeout(myFunction, 5000)
    })
    
    0 讨论(0)
提交回复
热议问题