javascript 如何在用户键入时延迟 KeyPress 功能,以便它不会为每次击键触发请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5913181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:46:11  来源:igfitidea点击:

How to delay KeyPress function when user is typing, so it doesn't fire a request for each keystroke?

javascriptjqueryajax

提问by DaveDev

background

背景

I have a number of dropdowns on a page. If you change the first one, the rest of the dropdowns are updated according to what you've selected.

我在一个页面上有许多下拉菜单。如果您更改第一个,其余的下拉列表将根据您的选择进行更新。

In our case, we deal with fund data. So the first dropdown is "All Fund Types". You select "Hedge Funds", and the next dropdown is filtered by options that only apply to Hedge Funds.

在我们的例子中,我们处理基金数据。所以第一个下拉菜单是“所有基金类型”。您选择“对冲基金”,下一个下拉列表将筛选出仅适用于对冲基金的选项。

The client is now asking me to put a text field into the mix, which when the user starts typing, will effect those results.

客户现在要求我将一个文本字段放入混合中,当用户开始输入时,它将影响这些结果。

So if they type "USD", the second dropdown will only contain options that have funds with "USD" in the name.

因此,如果他们输入“USD”,则第二个下拉列表将只包含名称中带有“USD”资金的选项。

problem

问题

The specific problem that I'm having is that with the code I'm using:

我遇到的具体问题是我正在使用的代码:

$('#Search').keypress(function () {
    // trigger the updating process
});

It's triggering the search for each key press. So when I type "USD" I'm getting 3 requests immediately - one for "U", one for "US" and one for "USD".

它会触发对每次按键的搜索。因此,当我输入“USD”时,我会立即收到 3 个请求——一个是“U”,一个是“US”,一个是“USD”。

I've tried setting a timeout with this:

我试过用这个设置超时:

$('#Search').keypress(function () { 
    // I figure 2 seconds is enough to type something meaningful
    setTimeout(getFilteredResultCount(), 2000);
});

but all that does is wait 2 seconds before doing what I've described.

但所做的只是等待 2 秒钟,然后再执行我所描述的操作。

I'm sure this problem has been solved before. Could somebody suggest how to solve this issue?

我确定这个问题以前已经解决了。有人可以建议如何解决这个问题吗?

回答by Tim Rogers

The way I have done this before is to set a timeout, but clear the existing timeout each time a new key is pressed. That way you should only get the request being sent when the user has stoppedtyping.

我以前这样做的方法是设置超时,但每次按下新键时清除现有超时。这样你应该只在用户停止输入时发送请求。

var timeoutId = 0;
$('#Search').keypress(function () { 
    clearTimeout(timeoutId); // doesn't matter if it's 0
    timeoutId = setTimeout(getFilteredResultCount, 500);
    // Note: when passing a function to setTimeout, just pass the function name.
    // If you call the function, like: getFilteredResultCount(), it will execute immediately.
});

(I'd go for about 500ms timeout.)

(我会去大约 500 毫秒超时。)