如何延迟.keyup()处理程序直到用户停止输入? [英] How to delay the .keyup() handler until the user stops typing?

查看:105
本文介绍了如何延迟.keyup()处理程序直到用户停止输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个搜索字段。现在它搜索每个keyup。因此,如果有人键入Windows,它将使用AJAX搜索每个键盘:W,Wi,Win,Wind,Windo,Window,Windows。

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", "Windo", "Window", "Windows".

我希望有一个延迟,因此它只会在用户停止输入200 ms时进行搜索。

I want to have a delay, so it only searches when the user stops typing for 200 ms.

没有 keyup 函数中的选项,我尝试过 setTimeout ,但它没有用。

There is no option for this in the keyup function, and I have tried setTimeout, but it didn’t work.

我该怎么做?

推荐答案

我用这个小函数来做相同的目的,在用户停止键入指定的时间后或在高速率的事件中执行函数,例如 resize

I use this small function for the same purpose, executing a function after the user has stopped typing for a specified amount of time or in events that fire at a high rate, like resize:

function delay(callback, ms) {
  var timer = 0;
  return function() {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      callback.apply(context, args);
    }, ms || 0);
  };
}


// Example usage:

$('#input').keyup(delay(function (e) {
  console.log('Time elapsed!', this.value);
}, 500));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="input">Try it:
<input id="input" type="text" placeholder="Type something here..."/>
</label>

延迟函数将返回一个内部处理单个计时器的包装函数,在每次执行中,计时器重新启动并提供时间延迟,如果在此时间过去之前发生多次执行,计时器将重置并重新开始。

The delay function will return a wrapped function that internally handles an individual timer, in each execution the timer is restarted with the time delay provided, if multiple executions occur before this time passes, the timer will just reset and start again.

当计时器最后结束,执行回调函数,传递原始上下文和参数(在本例中,jQuery的事件对象,DOM元素为 this )。

When the timer finally ends, the callback function is executed, passing the original context and arguments (in this example, the jQuery's event object, and the DOM element as this).

对于更复杂的东西,请查看jQuery Typewatch 插件。

For something more sophisticated, give a look to the jQuery Typewatch plugin.

这篇关于如何延迟.keyup()处理程序直到用户停止输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆