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

Transforming JSON data from JavaScript to Python JSON format

I am working with JavaScript JSON data: var data = '{a: 10, b: 20}' Now I need to convert this into Python JSON. Any suggestions on how to achieve this? Current Scenario: I have a script that extracts text from a website. The data on the webs ...

When using @mouseover, it is not possible to modify a variable's value

The hover event is not functioning properly in this Vue component. Although I was able to call a function on hover successfully, I encountered issues when trying to change the hover variable directly. <template> <div @mouseover="hover = t ...

Extract the String data from a JSON file

valeurs_d = ""; for (var i = 0; i < keys.length -1 ; i++) valeurs_d += + event[keys[i]] + ", "; var str5 = ","; var str6 = str5.concat(valeurs_d); var valeurs = str6.sub ...

Issue with JavaScript not executing upon clicking the submit button on a form within the Wordpress admin page

In the admin pages of my Wordpress installation, I have created an HTML form. My goal is to validate the data inputted when the submit button is pressed using a Javascript function. If the data is not correctly inserted, I want alerts to be displayed. Desp ...

Injection of Angular state resolve into controller fails to occur

I'm attempting to ensure that the value from ui-router's resolve is successfully passed to the controller portalsForUserCtrl. Take a look at the router code below: (function () { 'use strict'; var myApp = angular.module("myApp", ["co ...

Trap mistakes while utilizing async/await

Within my Express application, I have a register function for creating new users. This function involves creating the user in Auth0, sending an email, and responding to the client. I am looking to handle errors from Auth0 or Postmark individually and send ...

How to retrieve the value of a SelectField component within a constant using Material-UI

I am currently facing an issue with my Drawer component that contains a SelectField with some fields. I am struggling to get the value and implement the onChange functionality of the Field. Below is the snippet of my code: const DrawerCargoAddItem = (p ...

Using regular expressions in JavaScript to work with numbers separated by commas, as well as their comparison operators such as greater than, greater than or

Currently, I have implemented this Regex pattern to validate numbers with decimals (comma separated) /(^\d*\,?\d*[1-9]+\d*$)|(^[1-9]+\d*\,\d*$)/ However, I am now faced with the need to modify it in order to also valida ...

Is it possible to utilize a keyboard listener to activate a tooltip upon being invoked?

I've created a basic pie chart that shows a tooltip when you click on a pie wedge. Now, I want to achieve the SAME functionality, but for div elements located OUTSIDE of the pie chart. Situation: A user focusing on the 'Cat 1' div and ...

"Passing the v-model property to a child component in Nuxt.js: A step-by-step

I seem to be having trouble passing dynamically modified properties from layouts into the <Nuxt /> component. This is my ~/layouts/default.vue <template> <div> <input v-model="myprop" /> <span>{{myprop}}< ...

Issues with table formatting and malfunctioning functions

I created a basic tic-tac-toe game, but I'm having an issue with the table display. It appears squished when the game loads. Is there a way to prevent this and keep the table empty? Additionally, I am using NotePad++ and encountering problems running ...

What is the method to retrieve the ID name of an HTML tag based on its value?

Is there a way to determine the ID of an HTML tag based on its content? For example, if I have the following textboxes: I need to identify the id with the value "A2" So the expected result is id=option2 because its value is A2 <input type="text ...

Struggling to make fadeIn() function properly in conjunction with addClass

I've been struggling with this issue for quite some time now and I just can't seem to make it work. The JavaScript I'm working on involves using addClass and removeClass to display and hide a submenu element. While the addclass and removeCla ...

Transmitting information to the service array through relentless perseverance

I need assistance finding a solution to my question. Can my friends help me out? What types of requests do I receive: facebook, linkedin, reddit I want to simplify my code and avoid writing lengthy blocks. How can I create a check loop to send the same ...

Dealing with unexpected modifications in a React class component

In short, I need to adjust the data in my class component before sending it to the server to match the API request format. To achieve this, I created a method called transformData within my class component which transforms the data extracted from the state ...

The Bootstrap toast fails to appear on the screen

I am currently working on a website project using HTML with bootstrap and javascript. I have been attempting to include a toast feature by implementing the code provided on the bootstrap website: <div class="toast" role="alert" aria-live="assertive" ...

Using RxJS with Angular to intercept the valueChanges of a FormControl prior to subscribing

I decided to create a new observable using the values emitted by the FormControls.valueChanges observable. This creation of the observable takes place within the ngOnInit method in the following manner: ngOnInit(): void { this.myObservable$ = combine ...

Issue with authentication and cross-origin resource sharing (CORS) when implementing Spring Boot, Spring Security, Vue.js,

Running on vue.js 3, Vite 4.0.2, axios 0.25.0, and spring boot (Starter 2.7.2). A backend has been created in spring boot while using vue.js3, vite, and axios for the UI. Now, I simply want to make a call to rest with axios. Before implementing these func ...

Unending redirections caused by Nuxt middleware

I've implemented a middleware that checks the user's registration step and redirects them to the appropriate page. Here is my code: export default function ({app, redirect, route}) { let auth = app.$auth; console.log('step checks mi ...

The jQuery .post method is not returning any data when using the done and fail functions

I've encountered an issue while attempting to execute a jQuery AJAX request and retrieve the data in the .done and .fail methods. Below is the snippet of code that triggers the AJAX request: async function doSomething(){ const addressValid = awai ...