What is the best method to trigger a reevaluation of static parameters?

Explanation behind my question

Every day, I am sent two timestamps through MQTT at 01:15 - these timestamps represent the beginning and end of a daily event (in this case, when my children are at school). It may not be the most exciting information for a home dashboard, but it serves its purpose.

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

Currently, my dashboard displays 9:00 → 17:10, updating whenever new MQTT messages are received and the values for start and end change.

This functionality works well.

Now, I want to enhance the display to show additional information as follows:

9:00 → 17:10 (in 27 minutes)

The part in parentheses represents the time remaining until the end of the school day (17:10). I have the necessary logic to compute and display this information, with the condition that it should only be visible when "now" is within the specified timeframe.

This is achieved by using the following code snippet:

{{ extractTime(enfant.start) }} → {{ extractTime(enfant.end) }} <span v-if="dansCreneau(enfant.start, enfant.end)">({{dansTime(enfant.end)}})</span>
  • extractTime converts an ISO date to a 24-hour time format
  • dansCreneau returns true if "now" is between the specified dates, otherwise returns false
  • dansTime provides a human-readable representation of the time remaining until the end of the school day

The Issue I'm Facing

I can successfully display this information once, with a single calculation determining what goes inside the parentheses. However, from Vue's perspective, there is no compelling reason to recalculate it unless something changes.

I've considered using setInterval(XXX, 55000); for continuous updates and I'm unsure about what XXX should entail. Initially, I thought of reassigning enfant = enfant within the interval function, but this wouldn't trigger a recalculation since the value of enfant remains the same.

What would be the correct approach to force the recalculation and update of the remaining time?

Answer №1

To keep track of the current time, store it in the component's data and create a computed property that calculates the time difference between the stored current time and another time value.

Continuously update the current time using setInterval...

Here is an example of a simple clock implementation:

new Vue({
  el: '#clock',
  data: {
    currentTime: new Date(),
    timer: null
  },
  computed: {
    displayTime: function() {
      return this.currentTime.toLocaleTimeString();
    }
  },
  mounted: function() {
    let self = this;
    this.timer = setInterval(function() {
      self.currentTime = new Date()
    }, 1000)
  },
  beforeDestroy: function() {
    clearInterval(this.timer)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>

<div id="clock">
  <div>{{ displayTime }}</div>
</div>

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

In Typescript, if at least one element in an array is not empty, the function should return false without utilizing iterators

My current approach involves receiving a string array and returning false if any of the elements in the array is false. myMethod(attrs: Array<String>) { for (const element of attrs) { if (!element) { return false; } } ...

"Enhancing user experience with React.js and Socket.io: dynamically updating list item positions based on

export default class ReactApp extends React.Component { constructor(props) { super(props) this.state = { status: [], services: [] } fetchData((err,opt, data) => { function Exists(l ...

Tips for successfully passing store state as a prop in React-Redux with TypeScript

Having trouble passing information from the initial state of the store to a component where it's supposed to be rendered. Despite a console.log in the component showing that it's undefined, there doesn't seem to be any issue with the initial ...

Understanding how to open a PNG file in the client-side browser and transform it using PNGJS in React

Utilizing React JS for my application development is a current focus of mine. I have a solid understanding of how to import images within the client/browser folder structure. For example: import maze_text from '../../mazes/images/maze_text.png&apos ...

Adjust the node_modules path tailored to your project

My current project structure looks like this: |-app |-... |-libs |- package.json |- index.html I am interested in organizing my project such that the 'node_modules' folder is inside the 'libs' folder. The desired structure is as fo ...

Best method for reverting react-native to previous version

Here's the dilemma I'm facing: I had a functional version of a react-native project that was running smoothly and committed to my git repository. Deciding to upgrade from react-native 0.26.3 to 0.28 led me into a tangled web of dependencies, so ...

Uncontrolled discord bot flooding with messages despite being set to send messages only once every 60 seconds

const Discord = require('discord.js'); const { Client, MessageAttachment } = require('discord.js'); const client = new Discord.Client(); client.once('ready', () => { console.log("Ready!") }) client.on(&apos ...

What is the best way to divide text into key-value pairs using JavaScript?

I have data in text format from my Raspberry Pi that I need to insert into MongoDB as key-pair values or JSON for my Node.js Application. I'm relatively new to JavaScript and I'm looking for a solution. Any suggestions would be greatly appreciate ...

Monitoring and recording user's browsing activities while excluding server-side scripting

Currently, I am working on creating a registration form which will direct users to a "Thank you" page once completed. However, I want to include a button on this confirmation page that will take users back to the previous page they were on before registeri ...

Is it possible to utilize the router.query feature in a function within Next.js?

Running into a problem with my Next.js page. I'm attempting to utilize the request params in a function, but it keeps coming up as undefined. I've exhausted all my troubleshooting options. I already know that there's no need to include id i ...

vue-chartjs is experiencing difficulties when it comes to showing the labels and datasets

I'm having an issue with my line-chart. The data from the api/controller isn't showing up on the chart, even though the response contains all the data. https://i.stack.imgur.com/PWZxZ.png As shown in the image, the line-chart is empty but the r ...

Clicking on an element in React Material UI Autocomplete will bring it

I'm currently working with a material-ui autocomplete element <Autocomplete id="combo-box-demo" autoHighlight openOnFocus autoComplete options={this.state.products} getOptionLabel={option => option.productName} style={{ width: 300 ...

Is there a potential impact on performance when utilizing local variables instead of repeatedly accessing properties?

Examining JavaScript code optimized for a performance-sensitive environment, specifically a game engine in mobile settings. Oftentimes, this code avoids using local variables and instead relies on explicit chains, such as: if (this.x.y[z].i) { this.x ...

Attempting to invoke setState on a Component before it has been mounted is not valid - tsx

I've searched through various threads regarding this issue, but none of them provided a solution that worked for me. Encountering the error: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a b ...

When using AngularJS services to pass data, the data may be lost when the page is refreshed

I'm facing an issue with transferring data from controller A to controller B using a Factory (or a Service) when the user refreshes the browser. I am able to successfully set the data in controller A and retrieve it in controller B, but upon refreshin ...

What are the steps to resolve the vulnerability within vue-cli-service?

Recently, I set up a new project using @vue/cli 4.3.1 on a fresh installation of Ubuntu 19.10 with npm 6.14.4. Upon running npm install in the project directory, I received the following message: found 1 high severity vulnerability run `npm audit fix` t ...

AngularJS allows you to toggle the visibility of a div at set intervals, creating

I am struggling with the task of showing and hiding a div that serves as an alert for my application. Currently, I am using $interval to create a continuous show and hide action on the div. However, what I aim for is to have the DIV visible for X amount o ...

Asynchronously retrieving results in MongoDB

My task involves fetching all users from the users collection. app.post('/login', function(req,res,next){ users = self._db.get('users', {}) }) Below is the function in my database class: this.get = function( col, opt ) { ...

Function returning undefined when accessing prototype property in JavaScript

When attempting to create an image rotator using prototypal inheritance, I am encountering an error in the console showing: TypeError: this.curPhoto is undefined this.curPhoto.removeClass('previous'); I have placed this code in the callb ...

It appears that you are utilizing the runtime-only version of Vue, which does not include the template compiler

When attempting to build my Vue.js application using webpack, a warning appears in the browser. The warning states: "You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render f ...