Tengo el siguiente código en una aplicación vue
mounted: function () { this.timer = setInterval(async () => { if (this.progress >= 1) { this.progress = 1 clearInterval(this.timer) } console.log('update') const id = this.$route.params.id const progOut = await this.api.get(`/api/mu/job/${id}/status`) const response = progOut.data this.progress = response.data.progress / 100 this.state = response.data.status }, 7000) }, Esperaba que ejecutara la solicitud de get cada 7 segundos, pero está ejecutando la llamada cada 500 ms aproximadamente
Leí otras respuestas y hasta ahora creo que esta es la forma correcta, pero el código está ejecutando demasiadas solicitudes.
¿Cuál es la forma correcta de llamar a una función desde setInterval para que realmente espere el tiempo de espera?
Editar: este fue mi código final en caso de que alguien pase por lo mismo
methods: { redirect (page) { if (page === 'FINISHED') { this.$router.push({ name: 'viewReport', params: { id: 4 } }) } else { this.$router.push({ name: 'errorOnReport', params: { id: 13 } }) } } }, watch: { state: async function (newVal, old) { console.log('old ' + old + ' newVal ' + newVal) if (newVal === 'FAILED' || newVal === 'FINISHED') { this.redirect(newVal) } } }, data () { return { state: null, timer: null, progress: 0.0, progressStr: '0%' } }, mounted () { const update = async () => { if (this.progress >= 1) { this.progress = 1 } console.log('update ' + new Date()) const id = this.$route.params.id const progOut = await this.api.get(`/api/mu/job/${id}/status`) const response = progOut.data this.state = response.data.status this.progress = response.data.progress / 100 this.progressStr = response.data.progress + '%' } update() this.timer = setInterval(update, 10000) }, beforeUnmount () { clearInterval(this.timer) }Un mejor diseño es envolver setTimeout con una promesa y hacer el sondeo en un método asíncrono que se repite...
mounted: function() { this.continuePolling = true; // suggestion: we have to stop sometime. consider adding continuePolling to data this.poll(); }, unmounted: function() { // almost the latest possible stop this.continuePolling = false; }, methods: async poll(interval) { const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); while(this.continuePolling) { await this.updateProgress(); await delay(7000); } }, async updateProgress() { const id = this.$route.params.id const progOut = await this.api.get(`/api/mu/job/${id}/status`) const result = progOut.data.data; this.progress = result.progress / 100 this.state = result.status }