上次按键后2秒的Jquery运行代码 [英] Jquery Run code 2 seconds after last keypress

查看:84
本文介绍了上次按键后2秒的Jquery运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为网站开发自动搜索功能.

I am working on a auto search function for a site.

它使用ajax查询api.

It uses ajax to query an api.

输入3个字符后,每次按键时都会进行搜索.

At the moment after 3 characters are entered it will search on every key press.

我想要的是

案例1:
用户输入tes
2秒过去 搜索已执行


案例2:
用户输入tes
1秒通过
用户按下t
2秒过去
搜索在测试中执行

案例3:
用户输入tes
1秒通过
用户按下t
1.5秒通过
用户按下i
1.5秒通过
用户按下n
1.5秒通过
用户按下g
2秒过去
在测试中执行搜索

Case1:
User enters tes
2 seconds pass search performed


Case2:
User enters tes
1 second pass
user presses t
2 seconds pass
search is performed on test

Case3:
User enters tes
1 second passes
user presses t
1.5 seconds pass
user presses i
1.5 seconds pass
user presses n
1.5 seconds pass
user presses g
2 seconds pass
search in performed on testing

如您所见, 仅在按键后两秒钟内没有按键(或粘贴)的情况下,才执行搜索动作.

so as you can see, the search action is only performed when there has been no key presses(or pastes ect) in the two seconds following a key press.

我的基本想法是.

调用设置超时的函数, 该函数还设置一个变量,该变量包含文本框中的最后一个条目. 超时到期后,它将检查框中的值,以查看其是否与变量中的值匹配.

on keydown Call a function that sets a timeout, the function also sets a variable containing the last entry in the textbox. when the timeout expires it checks the value in the box to see if it matches the value in the variable.

如果它们匹配,则没有变化. 搜索也是如此

If they match then there has been no change. So do the search

如果他们什么都不做,则因为随后的按键超时将继续执行相同的检查.

If they dont then do nothing, because the timeout from the subsequent key press will be following to do the same check.

这是唯一/最好的方法吗?

Is this the only/best way to do this?

推荐答案

在前面的代码中,f是您要限制的函数,而delay是上次调用后要等待的毫秒数(如果省略,默认为500). throttle返回一个包装器函数,该函数清除先前调用中的所有现有超时,然后将超时设置为将来delay毫秒以调用f.对返回的函数的arguments的引用用于调用f,以确保f接收到期望的参数.

In the preceding code, f is the function you would like to throttle and delay is the number of milliseconds to wait after the last call (defaults to 500 if omitted). throttle returns a wrapper function that clears any existing timeouts from previous calls and then sets a timeout for delay milliseconds in the future to call f. A reference to the arguments of the returned function is used to call f with, ensuring f receives the arguments it is expecting.

您应按以下方式使用它:

You should use it as follows:

$('#search').keyup(throttle(function(){
    // do the search if criteria is met
}));

这篇关于上次按键后2秒的Jquery运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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