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

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

问题描述

我正在开发一个网站的自动搜索功能.

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:
用户输入测试
2秒过去执行搜索


案例 2:
用户输入测试
1 秒传球
用户按下 t
2秒过去
在测试上执行搜索

案例 3:
用户输入测试
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?

推荐答案

以下函数来自 Remy Sharp 会解决问题:

The following function from Remy Sharp will do the trick:

function throttle(f, delay){
    var timer = null;
    return function(){
        var context = this, args = arguments;
        clearTimeout(timer);
        timer = window.setTimeout(function(){
            f.apply(context, args);
        },
        delay || 500);
    };
}

在前面的代码中,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
}));

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

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