Execute function periodically using Vue.js

I have a requirement to update data periodically by calling a function in my Vue.js application. I am looking to call the 'listar()' method every 30 seconds and store the response in a property of vue js.

If anyone can guide me on where to locate this property in vue js, I would greatly appreciate it. I will explore all the comments for insights.

<script>
  export default {
    methods: {

            listar(){
            let me=this;
                me.mesas=[];
                axios.get('api/mesas/ListarTodos').then(function(response){
                    //console.log(response);
                    me.mesas=response.data;
                      me.loading=false;
                }).catch(function(error){
                    console.log(error);
                });



        },
}
</script>

However, the initial implementation did not work as expected.

setTimeout(() => {
         //
}, 300)

Update:

The latest code implementation works well for me, but there is an issue with the polling method when navigating to another page in our single page application (SPA). The setInterval continues running even after switching pages.

I tried using clearInterval() but it doesn't stop the method from executing once I change the component/page. It only clears the interval the first time I switch pages.

For more information, you can refer to the following link:

<script>
import axios from 'axios'
  export default {

data () {
      return {
        polling: null,

       },
methods: {

        listar(){
                let me=this;
                    me.mesas=[];
                    axios.get('api/mesas/ListarTodos').then(function(response){
                        //console.log(response);
                        me.mesas=response.data;
                          me.loading=false;
                    }).catch(function(error){
                        console.log(error);
                    });



     pollData () {
      this.polling = setInterval(() => {

         this.listar();
       }, 3000) },

                },


 created () {
      this.pollData()

    },

 beforeDestroy () {
         clearInterval(this.polling)
    },
  }
</script>

Answer №1

As mentioned by ittus, the recommended approach is to utilize setInterval:

setInterval(() => {
    // call listen()
}, 30 * 1000);

The setInterval function gives you an object that can be used with clearInterval to stop invoking listen.

If you also need to consider the timing of the request, you could incorporate setTimeout within a .finally block at the conclusion of your (promise) request:

axios.get('api/mesas/ListarTodos').then(function(response){
    //console.log(response);
    me.mesas=response.data;
    me.loading=false;
}).catch(function(error){
    console.log(error);
}).finally(function(){
    setTimeout(/*call listen in a function*/, 30 * 1000);
});

In any case, this aspect is not directly related to vuejs.

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

Error Found: Unexpected Colon (:) in Vue TypeScript File

Important Update: After thorough investigation, it appears that the issue is directly related to the boilerplate being used. As a temporary solution, it is recommended not to extract the TypeScript file but keep it within the .vue file for now. In a sim ...

JavaScript timekeepers and Ajax polling/scheduling

After looking into various methods like Comet and Long-Polling, I'm searching for a simpler way to push basic ajax updates to the browser. I've come across the idea of using Javascript timers to make Ajax calls at specific intervals. Is this app ...

Utilizing Node Js and Selenium webdriver, what is the process of dragging and dropping an element from its current position to a new position just below it?

After multiple attempts, I have come to realize that the following code is ineffective. driver.findElement(By.xpath(xpath)).then(function (element1) { driver.findElement(By.xpath(xpath)).then(function (element2) { ...

Issue with Vue class binding failing to update when state is modified

I'm attempting to utilize Vue class binding depending on the index within the v-for loop. While I can see that the state in Vue dev tools is changing correctly, the class name itself isn't being updated. <div class="group" v-for= ...

Updating SVG colors using VueJS

I'm struggling to change the color of an existing static SVG image. Here's the code I have: <img class="icon-shop" src="@/assets/icon-shop.svg"/> <style> .icon-shop { width: 32px; fill: orange; stroke: oran ...

Tips for implementing an autoscroll feature in the comments section when there is an abundance of comments

Having a large number of comments on a single post can make my page heavy and long sometimes. This is the current layout of my post comment system: Post 1 Comment for post 1 //if comments are more than 3 <button class="view_comments" data-id="1">Vi ...

When the onClick event on one element triggers a change in another element within the

I apologize if the title is not clear. I have a React component with buttons and text, which I have used three times. My goal is for each button to display its respective text when clicked, while hiding the texts associated with the other buttons. While m ...

Struggling to retrieve data with arrow function in Vue

I'm currently learning Vue and facing an issue with fetching data from an API to my component. I have a service class that successfully retrieves data from the API, as the API itself is working fine. Here's the code snippet: import IReview from & ...

Tips for sending parameters to XSLT using a Javascript function

Despite my efforts to find a solution in various online posts, I haven't been able to resolve the issue. The challenge lies in my HTML file that includes a JavaScript function for parsing XML and rendering XSLT. I have multiple 'records' in ...

Is the script failing to retrieve the innerHTML content?

Here is a snippet of HTML code: <div id="team_players"> <h3>Players</h3> <button class="bold-btn" onclick="teamAct('player_list');">Refresh List ↻</button> <table> <thead> <tr> ...

Passing a Javascript variable to the NAME attribute of an HTML <a href> tag: Steps to do it efficiently

I need assistance with passing a JavaScript variable to the NAME attribute of an HTML tag. Let's consider this script example: <script> var name = "Click here!"; </script> My goal is to pass the variable to some code in order for <a ...

How can I position two divs side by side within an Appbar?

I would like the entire Container to be in a single row, with the Typography centered as it already is, and the toggle-container to float to the right <AppBar className={styles.AppBar}> <Toolbar> <Container> ...

What is the best method for transferring properties to the parent component using Vue router?

I have a multi-step form that each step has a different header structure. The only variation in the header among the steps is the wording, which changes as you progress through the steps. I am looking for a way to achieve this using Vue Router: pa ...

Troubleshooting Vercel and Express DELETE request cross-origin resource sharing problem

Currently, I am in the process of developing an API using Vercel and ExpressJS. The GET and POST endpoints are functioning properly, however, I encountered an issue with the DELETE endpoint. When attempting to access the endpoint from my client-side JavaSc ...

Upcoming verification with JSON Web Token

I am looking to incorporate JWT auth into my Next app. Currently, I have mapped out the flow as such: User enters email and password to log in Server responds with status 200 and a jwt access token in httpOnly cookies My main dilemma lies in deciding on ...

Mastering the management of various events within React Material UI components

I am working with a Material UI Switch Component and need to detect click events on it. In certain situations, I want to prevent the change event from triggering. What is the most effective way to achieve this? While I have previously used event.preventD ...

Tips for adjusting the up and down controls and spins of a date input after modifying its height

After adjusting the height of my inputs (date type) to 40px, I noticed that the up and down controls are no longer aligned with the text inside the field. I am looking for a solution to either adjust the height of the spins or remove them if necessary in ...

What might be causing the issue of not being able to access req.body using multer?

In my application built using vue, users have the ability to upload files along with some data to my node backend. Once the user submits the form, the following function is executed: methods: { buttonOK () { const formData = new FormData() ...

Guide on incorporating the Chain Pattern alongside the Self Revealing Module Pattern within JavaScript

I have come across the following code snippet: filtersManager = (function ($) { var that = this; function initialize() { // some tasks return that; }; function execute() { // some tasks return that; ...

"Enhance your Angular JS experience with dynamic URL parameters and personalized redirection for improved URL accessibility

I'm struggling to make this code function properly: ..... .when('/channel/:id/:slug',{ templateUrl:'views/channel/index.html', controller:'Channel', publicAccess:true, ...