Reddy
Reddy

Reputation: 21

Throttling a jQuery .load() function for autocomplete

I use the following function to get autocomplete suggestions as a user types from a PHP file using jQuery .load().

How should I throttle the number of autocomplete requests being made with this function if a user is typing really fast? I'm new to this sort of thing.

<script>

function getSuggestions(){
    var query = document.getElementsByName("q")[0].value;
    $(document).ready(function(){
        $("#suggestions").load("https://example.com/autosuggest.php", {
            q: query
        });
    });
}

$(document).ready(function(){
    let debounce;
    $('.searchBox').on('keydown', function(e){
        // get keycode of current keypress event
        var code = (e.keyCode || e.which);

        // do nothing if it's an arrow key
        if(code == 37 || code == 38 || code == 39 || code == 40 || code == 13) {
            return;
        }

        // do normal behaviour for any other key
        debounce = setTimeout(() => {
            getSuggestions();
        }, 350);
    });
    $(".searchBox").click(function(){
        getSuggestions();
    });
});

</script>

<input class="searchBox" type="text" name="q" placeholder="" value="" onkeydown="getSuggestions()">

<div id="suggestions">

</div>

Upvotes: 1

Views: 184

Answers (1)

dave
dave

Reputation: 64657

The general concept is called "debounce" - and basically you just have to set a timeout and wait to make the request for say, 500 milliseconds. Every time you receive input, you clear the timeout. Then, once they've finally stopped typing for a bit, the timeout will get triggered. Something like this (where I'm just logging the input, but you can see that it only triggers when you stop typing):

$(function() {
    let debounce;
    $('.searchBox').on('input', function() {
        clearTimeout(debounce);
        debounce = setTimeout(() => {
            const value = $(this).val();
            console.log({value});
            /* $("#suggestions").load("https://example.com/autocomplete.php", {
                q: value
            }); */
        }, 500);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input class="searchBox" type="text" name="q" placeholder="" value="">

<div id="suggestions">

</div>

Upvotes: 1

Related Questions