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

查看:24
本文介绍了如何延迟 .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 毫秒时搜索.

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>

delay 函数将返回一个封装的函数,该函数在内部处理一个单独的计时器,在每次执行时,计时器会以提供的时间延迟重新启动,如果在此时间过去之前发生多次执行,计时器将只需重置并重新开始.

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).

我已经使用 ES5 和 ES6 特性为现代环境重新实现了该功能:

I have re-implemented the function using ES5 and ES6 features for modern environments:

function delay(fn, ms) {
  let timer = 0
  return function(...args) {
    clearTimeout(timer)
    timer = setTimeout(fn.bind(this, ...args), ms || 0)
  }
}

该实现包含一个测试集.

要了解更复杂的内容,请查看 jQuery Typewatch 插件.

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

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

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