I am trying to execute an API call 3 seconds after the last modification of a variable in Vue.js.
I implemented this using setTimeout
and clearTimeout
with a watcher
on my variable :
data () return {
timeoutDuration: null,
}
watch: {
queryGeocodage: function (value) {
if (this.timeoutDuration) clearTimeout(this.timeoutDuration)
await // async stuff
this.timeoutDuration = setTimeout(() => { console.log('timeout') }, 2000)
}
}
The console.log
still execute as many time as queryGeocodage
change like if the timeout wasn't clear.
Why the timeout isn't cleared?
Guess:
Because queryGeocodage() is async function, when queryGeocodage change before await // async stuff
completed, this.timeoutDuration is not assgined. So clearTimeout() is not executed.
You can try to log the value of this.timeoutDuration to explore it.