What is causing this setInterval function to run repeatedly?

Below is the code snippet from my 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)
  },

The issue I'm facing is that instead of executing the get request every 7 seconds, it seems to be making the call approximately every 500ms. Despite going through other answers, I believe this is the correct approach but there are too many requests being made.

I want to know the right way to make a function within the setInterval actually wait for the timeout before executing again.

Edit: Here's the final revised version of my code in case it helps someone dealing with a similar situation:

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

Answer №1

An improved approach involves encapsulating setTimeout within a promise, and conducting the polling within an asynchronous method that iterates...

mounted: function() {
  this.continuePolling = true;  // note: it's important to eventually stop. Consider adding continuePolling to data
  this.poll();
},

unmounted: function() {         // one of the last points where we can halt
  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
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customizing the CSS of the TinyMCE editor within a React application

Incorporating TinyMCE 5 into my React project has been an interesting challenge. I'm looking to personalize the editor by adjusting elements like borders and adding box shadows to the toolbar. Despite attempting to add CSS through the content_css prop ...

Property finally is missing in the Response type declaration, making it unassignable to type Promise<any>

After removing the async function, I encountered an error stating that the Promise property finally is missing when changing from an async function to a regular function. Any thoughts on why this would happen? handler.ts export class AccountBalanceHandle ...

Connecting a Kendo Dropdown menu to external data sources for seamless integration

I need help with binding data to a dropdown list for my local service. Whenever I try to download the data, I keep getting an error message: Uncaught SyntaxError: Unexpected token: Does anyone have any ideas on how to resolve this issue? This is my JS ...

Retrieve identical values from an array and display them using Vue.js

I am working with a product array that includes id, name, and category data for 5 products. For example, let's say there are 3 products assigned to the mobile category and 2 products assigned to the computer category. What is the best approach to rend ...

Dealing with throwing Exceptions in jest: A guide for developers

I have developed a method that throws an exception when the provided password does not match a regex pattern. I attempted to handle this in Jest. it('Should prevent insertion of a new user if the password doesn't match the regex', async () ...

Scrolling to the active list item in the navigation bar

Having an unordered list with the id mainul in the navigation bar is causing a problem when the page reloads. The navigation bar always starts at the beginning, but I would like it to automatically scroll to the active li element. This is my HTML code: & ...

What is the process for cancelling an interval when it is disabled in my configuration file?

To automate a bot, I want it to stop running an interval if the configuration file specifies "off" and continue running if it says "on". I attempted this: Using discord.js: config.Interval = setInterval(() => { WallCheck.send(WallCheckemb ...

A step-by-step guide on creating a live crud application with vuex and socketio

I am struggling to achieve a realtime crud operation using vuex, node, express, and socketio with the current syntax provided. Here is the code snippet: Server index.js const server = app.listen('3000',() => { console.log('<--- ...

Navigate to the second level array within the JSON data structure

As someone more inclined towards design rather than programming, any assistance is highly appreciated. The main goal of this project is to create a dropdown menu using the "name" field from the JSON data and display the corresponding "stock" information wh ...

Assistance with offsetting a jQuery drop down menu

This is the third jQuery script that I've been working on. While parts of it have been inspired by other scripts, I'm now focusing on implementing a specific feature. I've dedicated 4 hours to solving the issue of displaying the submenu on ...

The error message I'm receiving is saying that the map function is not recognized for the posts variable (posts.map

I encountered a puzzling error, even though everything seems fine: posts.map is not a function import React from 'react' import { useSelector } from 'react-redux' export const PostsList = () => { const posts = useSelector(state = ...

Exploring the Power of Ajax Interceptor in Framework7-vue-cli

I have a challenge where I need to redirect all ajax requests with a status code of -1 in the response to the login screen. Despite my efforts, I am unable to monitor it. What steps should I take next? Appreciate your help. My approach: app.js Framework7. ...

Issue with rendering HTML tags when replacing strings within Ionic 2 and Angular 2

I am currently working with an array of content in my JSON that includes URLs as plain text. My goal is to detect these text URLs and convert them into actual clickable links. However, I'm facing an issue where even though the URL is properly replaced ...

Error: JavaScript alert box malfunctioning

I am facing an issue with my JavaScript code. I have successfully implemented all the functionalities and can change the color of an image background. However, I am struggling to prompt a pop-up message when clicking on an image using "onclick". I have tri ...

What is the best way to adjust the color of a button element?

I've been troubleshooting the mouseover function of my JavaScript button object. The goal is to have a function call (specifically show()) within the object that detects the mouseover event and changes the button's color to grey. I suspect that t ...

The Challenge of Iterating Through an Array of Objects in Angular Components using TypeScript

Could someone please explain why I am unable to iterate through this array? Initially, everything seems to be working fine in the ngOnInit. I have an array that is successfully displayed in the template. However, when checking in ngAfterViewInit, the conso ...

Linking query branches without encountering the "Exceeded the number of hooks rendered during the previous render" error

This apollo client utilizes a rest link to interact with 2 APIs. The first API returns the value and ID of a record, while the second API provides additional information about the same record. I combine this information to render the content without using ...

Select state and city options similar to the national breakdown page

I'm attempting to replicate a state and city selection box similar to the one on the NTTS Breakdown website. You can see it in action here: When you select a state on the left side of the webpage, the city selection box displays "loading data" and th ...

How to Create a Speech Bubble in SVG Using SnapSVG

In the process of developing a chat program, I have animated figures moving across the screen engaging in conversations. One crucial aspect I am yet to implement is creating scalable speech bubbles for when users interact. Being relatively new to SVG and ...

When the page is loaded, populate FullCalendar with events from the model

On page load, I am attempting to populate events with different colors (red, yellow, green) on each day of the calendar. Here is a simple example showcasing events for three days: I have data in a model that indicates the available amount of free pallets ...