Vue Search Inputs fires Fetch-Method every single keypressed [duplicate]

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.

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

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.

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


Solution 1:

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 stopped typing.

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