Jquery 在最后一次按键后 2 秒运行代码

发布于 2024-10-05 21:12:04 字数 711 浏览 0 评论 0原文

我正在为一个网站开发自动搜索功能。

它使用 ajax 来查询 api。

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

我想要的是

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

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

如你所见, 仅当按键后两秒内没有按键(或粘贴等)时,才会执行搜索操作。

我的基本想法是。

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

如果它们匹配,则没有任何变化。 因此,进行搜索,

如果他们不这样做,则什么都不做,因为随后的按键超时将遵循相同的检查。

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

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

It uses ajax to query an api.

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

What I want is

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.

my basic idea is to.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烂人 2024-10-12 21:12:04

Remy Sharp 中的以下函数可以解决这个问题

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);
    };
}

: code,f 是您想要限制的函数,delay 是最后一次调用后等待的毫秒数(如果省略,则默认为 500)。 throttle 返回一个包装函数,该函数清除先前调用中的任何现有超时,然后设置未来 delay 毫秒的超时以调用 f。对返回函数的参数的引用用于调用f,确保f接收到它所期望的参数。

您应该按如下方式使用它:

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

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);
    };
}

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
}));
裂开嘴轻声笑有多痛 2024-10-12 21:12:04

几乎相同,只是仅在满足条件时才设置计时器:

<input id="search" type="text" />
<script>
    var timer, value;
    $('#search').bind('keyup', function() {
        clearTimeout(timer);
        var str = $(this).val();
        if (str.length > 2 && value != str) {
            timer = setTimeout(function() {
                value = str;
                console.log('Perform search for: ', value);
            }, 2000);
        }
    });
</script>

Almost the same except that timer is set only when conditions are met:

<input id="search" type="text" />
<script>
    var timer, value;
    $('#search').bind('keyup', function() {
        clearTimeout(timer);
        var str = $(this).val();
        if (str.length > 2 && value != str) {
            timer = setTimeout(function() {
                value = str;
                console.log('Perform search for: ', value);
            }, 2000);
        }
    });
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文