Is the content of the function re-evaluated by setInterval()?

I am currently working on a beginner level single-page application (SPA) using Vue, specifically the Quasar framework.

In this application, during the mounted() lifecycle hook, it connects to an MQTT broker to retrieve some information. This information is stored in this.results, which becomes available asynchronously after some time.

I utilize the data from this.results in various components for display and ensure that it updates accordingly when new results are received.

Since this SPA serves as a frontend for a home monitoring system, I also wanted to include the timestamp of the last data retrieval and trigger alerts if no new results are obtained within a certain timeframe, indicating a possible backend failure. To implement this, I added the following code snippet:

mounted() {
    // Connect to the MQTT broker to receive new results. Alternatively, use setInterval with fetch()
    this.client = mqtt.connect("mqtt://mqtt.swtk.info:1884");
    this.client.on("connect", this.mqttConnect);
    this.client.on("message", this.mqttMessage);
    // Check every 900ms for the time elapsed since the last data retrieval and update the variable accordingly
    setInterval(
      function() {
        console.log(this.results)
        this.timeSinceLastRun = moment().unix() - moment(this.results.when).unix()
      },
      900
    )
}

Continuously, I see this message being logged in the console:

https://i.sstatic.net/AvkEQ.png

Simultaneously, even though this.results is indeed defined and its contents are correctly displayed in components, when inspecting the DevTool Vue tab, I notice:

https://i.sstatic.net/ZePQJ.png

It seems like within the setInterval() function, the value of this.result is evaluated only once and is initially set to undefined, which is expected since the data might not have been received at that point but will be updated shortly afterwards.

Shouldn't the current value of this.result be used in each call of the function within the 900ms interval?

Answer №1

Consider utilizing arrow functions () => {} in the following manner

setInterval(
      () => {
        console.log(this.data)
        this.timeElapsed = moment().unix() - moment(this.data.date).unix()
      },
      900
    )

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 can these lines be drawn in a simple manner?

I have been using the div tag to create a line, but I'm looking for an easier solution. If you have another method in mind, please share it with me. #line{ background-color:black; height:1px; width:50px; margin-top:50px; margin-left:50px; f ...

What is the best way to iterate through a list of element ids within an array and assign each one to a unique

I am currently in the process of restructuring my window.onload function to eliminate redundancy. My goal is to iterate through the elements I'm assigning to global variables using their ids. Initially, I successfully assigned onclick functions with a ...

The retrieval of data using PHP, MYSQL, and AJAX is unsuccessful

A dropdown menu contains the names of months, represented by numbers from 1 to 12: When a month is selected, I want to retrieve data from a database to display relevant tournaments for that specific month. The SQL code has been tested and confirmed to be ...

The JSP AJAX response comes back empty

I am encountering an issue where I am using JQuery Ajax to call a REST API in JSP, but it keeps returning null no matter how I try. Strangely enough, the same code works when used in HTML. I have been searching online for a solution but haven't found ...

Unable to confirm the absence of a variable in TypeScript

I can't seem to resolve the compiler error " Object is possibly 'undefined' " const destinationColumnIndex = (): number => { if (typeof result.destination === 'undefined') { return 0; } return boardData.findIndex( ...

Trouble arises when trying to load high-resolution images in Chrome on a Windows operating system using JavaScript

Having an issue with a website where I am progressively loading multiple images - starting with a smaller resolution image for faster loading and then ajaxing in a larger image (usually the original size uploaded by the user). The following code functions ...

"Sharing fields between mongoose models: How can I reference a field from one model in another

I am currently working on linking specific fields from the User model to the Card schema using the username as a reference point. Let me provide an example using my Card schema: const CardSchema = new mongoose.Schema({ text: { type: String, ...

Angular is having trouble finding the Gapi object

I have implemented the integration of google-docs into my application using Angular. I referred to the google-docs API link provided in the Javascript format https://developers.google.com/docs/api/quickstart/js <!DOCTYPE html> <html> <hea ...

the nodejs app cannot be launched as the port is already being utilized

I've encountered an issue while trying to run my nodejs app. It's displaying an error indicating that the port is already in use. I've made several attempts to resolve this problem by restarting the application. Error: listen EADDRINUSE: a ...

Steps to revert to the previous state in a ReactJS Class Component

I am working on a project that involves: An array of 44 object data Typing a returns 37 data immediately through the onChange() event After typing ad, it returns 20 The issue arises when I go back to typing just a using the backspace key. It ...

Determine the presence of a username and email in the MongoDB database

I am currently updating my code to validate if both the username and email already exist in my MongoDB database before adding a new user. Currently, the code successfully checks for existing emails but I am struggling to implement a check for usernames as ...

Lustrous Layout

I am developing a mobile app using titanium where I have a scroll view containing objects that occupy 25% of the screen width. I am attempting to create a 'table' layout with these objects, having 4 columns and multiple rows. Is there a way for t ...

Customize div styles according to the website domain

I want to dynamically change the header of my website based on whether it is in dev QA or production environment. Below is the HTML code: <div id="wrapper"> <form id="form1" runat="server"> <div class="wrapper"> <div> ...

The raycaster in Three.js seems to be having trouble selecting the correct object

Hey everyone, I'm currently working on selecting objects using a raycaster and I want to change the material of the first selected object. Everything works smoothly until I pick the object - when I select the first element, only one object changes. I ...

Implementing React and Material UI: Maximizing Vertical Space Usage for a Box Component

Currently, I am working on a web application using React combined with Material UI. Within my code snippet below, you will see three Box components in play. Box 1 and Box 3 have specific heights set, but I am looking for a way to make Box 2 occupy the re ...

Eliminate elements from an array within a promise

I am facing an issue with the currentBillCyclePath parameter in the following function. I need to use this parameter to filter out certain elements after executing the query. However, inside the while loop, the value of currentBillCyclePath is undefined. ...

The Next.js app's API router has the ability to parse the incoming request body for post requests, however, it does not have the

In the process of developing an API using the next.js app router, I encountered an issue. Specifically, I was successful in parsing the data with const res = await request.json() when the HTTP request type was set to post. However, I am facing difficulties ...

Create a sequence of reactions using Selenium WebDriver

I am looking to gather a set of responses while browsing a website, and then "recreate" the process using those responses. Upon exploring an different discussion, I stumbled upon this method for rendering HTML: content = requests.get("https://stackoverfl ...

Detection of the page rendering time for an angular spa application's final section

Our team is working with an angular SPA and we are seeking a solution to generate an event once a page has finished rendering and all ajax calls have been completed. We are open to any suggestions on how we can achieve this without having to implement it ...

What could be the reason Recaptcha is not displaying when called from PHP through XMLHttpRequest?

::CLARIFICATION:: When attempting to load a registration frame with a captcha check in an HTML file, the form displays correctly but the captcha does not appear. The following Javascript code is supposed to fetch the desired content, suggesting that there ...