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

How come the hidden container does not reappear after I click on it?

I'm having an issue with a hidden container that holds comments. Inside the container, there is a <div> element with a <p> tag that says "Show all comments". When I click on this element, it successfully displays the comments. However, cli ...

Jose authentication is encountering issues with verifying JWT

My Next.js/Clerk.js middleware setup looks like this: import { authMiddleware } from "@clerk/nextjs"; import { jwtVerify } from "jose"; export default authMiddleware({ publicRoutes: ["/", "/contact", "/pricin ...

Achieve identical outcomes with PHP's `strlen` function and jQuery's `val().length` method

Currently, I am utilizing jQuery to dynamically count the value of a textarea: function count_chars () { count_chars=$('#text_textarea').val().length; } Upon submission, I serialize the form and send the textarea text via AJAX to a PHP file ...

What are the steps to send $http requests from AngularJS to a local server in an app?

Situation at Hand My goal is to perform an $http post request from Angular using the function below, defined in my controller: $scope.sendUserData = function(){ var userData = JSON.stringify({ 'firstName': $scope.firstName, ...

Display a div based on search results

I recently encountered an issue with a script that needs modification to display different divs based on search criteria. Originally, I used this script for a contact list but now need it to perform another function. View the original code (JSFiddle) Here ...

Dynamically modifying the styling of elements within an iframe

In my current project, I encountered a challenge with changing the background color to black and the body text color to white within an iframe. Additionally, all elements that are originally styled with black in an external stylesheet also need to be chang ...

Unique browsing key

Is there a specific identifier that can uniquely represent the browser you are currently using? I have two applications logged in through ApiGateWay, and I need to determine whether they are both running on the same browser. Therefore, I require a unique ...

Utilizing a custom component within the Vue ais-hits feature

I have been working on implementing an Algolia search page, and initially, everything was functioning correctly with the following code: <ais-hits> <template #default="{ items }"> … </template> </ais-hits> ...

increasing the size of a picture without resorting to a pop-up window

Struggling to implement a product details tab within a table that features a clickable image. When the image is clicked, it should enlarge but the width doesn't adjust accordingly. I'm using bootstrap 5.3 and can't seem to identify the root ...

NextJS able to execute code on the client side after being called from the server side

I am currently using getStaticProps to retrieve data from the server at build time and pass it to my page component. The following call is made from my page component file: const getStaticProps: GetStaticProps = async (context) => { const pa ...

"Optimizing Performance: Discovering Effective Data Caching

As a developer, I have created two functions - one called Get to fetch data by id from the database and cache it, and another called POST to update data in the database. However, I am facing an issue where I need to cache after both the get and update oper ...

Utilizing JavaScript Callbacks in HTML Image Tags

Currently I am working on a small application and looking to include a YouTube section. I have come across a method for obtaining the user's YouTube icon: This is included in the head section of my code: <script type="text/javascript" src="http:/ ...

JavaScript's Array.map function failing to return a value

Here is a snippet of code from an api endpoint in nextJS that retrieves the corresponding authors for a given array of posts. Each post in the array contains an "authorId" key. The initial approach did not yield the expected results: const users = posts.ma ...

How can the Material UI select component be customized to automatically scroll to the top when all items are selected?

After implementing the material ui select feature, I observed that when all items are selected, closed, and then reopened, the scroll position is automatically moved to the end. Is there a way to prevent this and keep it at the top? Current display: http ...

Exploring the functionality of Next.js with Links and routes

Currently, I am facing an issue with the popover menu in my header that displays products. The problem arises when I click on a product in the list; it navigates correctly to the path "products/some-product" regardless of the selected item. However, if I a ...

Managing file sizes on the client side prior to transferring them to the server side

I am looking to implement client-side validation for file size. The current code only handles success, but I also want to address file size limitations. Right now, if a file exceeds 2MB, it results in a 500 (Internal Server Error) behind the scenes. Is th ...

The anchor tag fails to trigger the onClick function in React

I'm having trouble updating the component state in my React app when clicking on an anchor tag within the render method. I've attempted to bind the function in the constructor, but the console.log statement is still not being called. Here's ...

What is the best way to ensure email address validation is done perfectly every time?

Can someone assist me with validating email addresses correctly? I am able to handle empty fields, but now I need a way to identify and display an error message for invalid email addresses. How can I modify my validation process to check for improper email ...

unresponsive script caused by videoegg javascript code

Has anyone encountered a message like this before? "A script on this page might be occupied, or it could have stopped responding. You have the option to stop the script now, or you can wait to see if it finishes." No JavaScript errors are visible in the ...

Error: The function getAuth has not been defined - Firebase

I have included the code snippets from index.html and index.js for reference. The analytics functionality seems to be working fine, but I am facing an issue with authentication due to an error during testing. Thank you for your help. index.html <script ...