Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
Why this setInterval is executing multiple times?

I have the below code in a vue application

  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)
  },

I was expecting it to execute the get request every 7 seconds but it is executing the call every 500ms approx

I read other answers and so far I think this is the proper way but the code is executing too many requests

What is the proper way to call a function from within the setInterval to make it actually wait the timeout?

Edit: This was my final code in case someone goes through the same

  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)
  }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

A better design is to wrap setTimeout with a promise, and do the polling in an async method that loops...

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
  }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda