Only handle the Algolia query if they are the last one [Resolved]

I am binding my Algolia query search to the onInput event of my changes but in case of really slow connection, the results are coming after I typed multiple more characters.

I would like to flag my search query with a unique ID to make sure that once the query is coming back it is the last one and discard all the other result to show.

What I did is to have a global and a local variables:

And check as soon as I get the results to see if they matches.

var searchQueryID;

function performSearch(event) {
    if ( !== '') {
        var search = searchQueryID = Math.random();{...}, function(err, content) {
            if (searchQueryID === search) {
              // It is the last query made.

You can actually use the helper for that, it deals (among other things) with out-of-order query results. If I remember how it does it correctly, it keeps an array of the queries done, and only cares when the last one is resolved. It’s open source, so you can take a look at it.

A better option is probably to use InstantSearch though, there are versions for vanilla, React, Vue and Angular (link to all of them)