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

假装没事ソ 提交于 2019-11-28 03:04:38
CMS

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.

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

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)
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!