In an attempt to postpone an API call for fetching search results, I have implemented the use of setTimeout
and clearTimeout
methods in my Vue application.
A watcher has been set up on a search variable so that whenever it changes, the corresponding code executes as expected.
watch: {
search: function (search) {
var self = this;
if (search.length >= 1) {
if (this.time) {
console.log(this.time)
clearTimeout(this.time);
console.log(this.time)
}
this.time = setTimeout( self.searchAccounts, 500);
} else {
this.restoreAccounts()
}
},
The goal is to cancel the previous API call if the method is executed within the next 500ms. However, the problem arises when I quickly type 3 characters ("ABC"), resulting in 3 separate API calls with parameters q=A
, q=AB
, and q=ABC
. It seems like the timer is not getting cleared properly. Any suggestions on how to resolve this issue?
Edit: Even after changing the setTimeout
call to a reference, the issue of multiple function calls persists, leading to the execution happening 3 times.