Delay Instant Search Until the User Stops Typing in Vue

In instant search, the user doesn’t have to press the search button to submit their search. The search bar searches as they type. It’s all the rage these days, I guess.

Anyway, it’s kind of annoying when it will search as you type every_ single_ character_. It‘s also bad to make so many unnecessary requests to the server. What we want, is it to wait until maybe a second after we have typed the last character to perform the search.

//template sorta like this                
<template>
<input v-model="query" />
</template>
//Untested code follows!
<script>
module.exports = {
data: function (){
return {
query: "",
timeout: "",
awaitingSearch: false
}
},
methods: {
//This function calls your search endpoint
search: function(){
...
}
},
watch: {
//Will be called every time the user types a character and the "query" changes.
//Debounce then perform the search
query: function(){
//if the user continues typing before the timeout is up we clear the timer.
if (this.timeout){
window.clearTimeout(this.timeout);
}
//set the timer to wait 1 second before performing the search
this.timeout = setTimeout(() => {
this.search()
this.awaitingSearch = false;
}, 1000); // 1 sec delay
this.awaitingSearch = true;
}
}
}
<script>

The “awaitingSearch“ variable works really well when adding a loading component.

//mostly the same template
<template>
<input v-model="query" />
<div v-if="awaitingSearch">
<loader/>
</div>
<div id="results" v-if="!awaitingSearch">
...
</div>
</template>