为什么 clearTimeout 不会阻止我在 Vue JS 中执行函数
Why clearTimeout is not preventing the execution of my function in Vue JS
我试图在 Vue.js 中最后一次修改变量后 3 秒执行 API 调用。
我使用 setTimeout
和 clearTimeout
在我的变量上使用 watcher
实现了这个:
data () return {
timeoutDuration: null,
}
watch: {
queryGeocodage: function (value) {
if (this.timeoutDuration) clearTimeout(this.timeoutDuration)
await // async stuff
this.timeoutDuration = setTimeout(() => { console.log('timeout') }, 2000)
}
}
console.log
仍然执行与 queryGeocodage
一样多的执行次数,就像超时不明确一样。
为什么没有清除超时?
猜猜:
因为 queryGeocodage() 是异步函数,当 queryGeocodage 在 await // async stuff
完成之前更改时, this.timeoutDuration 不会被分配。所以clearTimeout()没有被执行。
您可以尝试记录 this.timeoutDuration 的值来探索它。
我试图在 Vue.js 中最后一次修改变量后 3 秒执行 API 调用。
我使用 setTimeout
和 clearTimeout
在我的变量上使用 watcher
实现了这个:
data () return {
timeoutDuration: null,
}
watch: {
queryGeocodage: function (value) {
if (this.timeoutDuration) clearTimeout(this.timeoutDuration)
await // async stuff
this.timeoutDuration = setTimeout(() => { console.log('timeout') }, 2000)
}
}
console.log
仍然执行与 queryGeocodage
一样多的执行次数,就像超时不明确一样。
为什么没有清除超时?
猜猜:
因为 queryGeocodage() 是异步函数,当 queryGeocodage 在 await // async stuff
完成之前更改时, this.timeoutDuration 不会被分配。所以clearTimeout()没有被执行。
您可以尝试记录 this.timeoutDuration 的值来探索它。