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.

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

Tips for implementing daterangepicker js in an Angular 2 project

I'm currently working on an Angular 2 project and I'm looking to integrate the daterangepicker.js library for a date range picker. If you're not familiar with it, you can find more information about the library here. Here's the HTML co ...

What is the process for releasing an NPM package to the NPM registry rather than the GitHub registry?

I have developed an NPM package available at - (https://github.com/fyndreact/nitrozen) The package was successfully published on the Github registry (), but I am looking to publish it on the NPM registry. However, I cannot locate the package in the NPM r ...

Exploring the benefits of WordPress integration with form caching and dynamic show/hide div

Within my Wordpress (3.8.1) website, I have created a form that includes a checkbox. When this checkbox is clicked, a hidden div appears on the screen, prompting users to provide additional information. The JavaScript code responsible for showing the hidd ...

How to create a basic calculator in AngularJS with two textboxes specifically designed for calculating squares?

My code snippet is as follows: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div ng-app="app"> <div ng-controller="Calcu ...

Error: Firebase is throwing an error stating that it cannot access the length property of an undefined property

I need help establishing a connection with Firebase. Here is the code snippet from firebase.js: import * as firebase from "firebase/compat/app"; const firebaseConfig = { apiKey: "***", authDomain: "***", projectId: &qu ...

Integrating Vue.js code into Laravel's Blade templates for enhanced functionality

I'm having trouble accessing data from a Vue component function in a Laravel blade template that includes the component. When I use this code, the page just loads as a blank page. However, if I remove the @ symbol from the blade span, the autocomplete ...

Experiencing a Node.js application issue with the error message "ERR

I'm encountering some serious challenges with a Node.js app that I am developing using Express, MongoDB, and Mongoose. Everything seemed to be functioning correctly last night when I used nodemon server.js to start the server. However, I'm now fa ...

Tips for creating nested master-detail or master-detail-detail queries in Loopback

My set up includes category and category_subs in a master-detail model, with the post model being linked to category_subs. I have successfully retrieved the master-detail information for both categories, but now I am unsure of how to include the post and e ...

What is preventing me from accessing the variable?

Having some trouble using a variable from JSON in another function. Can someone lend a hand? async function fetchData() { let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d'); let data = await response.js ...

What is the purpose of using double % in Java or JSP?

Yesterday, while reviewing some code, I came across a line that seemed very peculiar to me. In a JavaScript function, there is a condition checking for a string passed as a parameter in the following manner: "%%unsubscribe%%". See the snippet below for re ...

Leveraging React Hooks' useEffect to trigger a prop callback function defined with useCallback

Currently, I am working on developing a versatile infinite scrolling feature using React Hooks along with the ResearchGate React Intersection Observer. The main concept revolves around a parent passing down a mapped JSX array of data and a callback functio ...

Increasing values in Mongoose using $inc can be done by following these steps

I've been struggling to increment a field value using $inc in my code. My schema looks like this: var postSchema = mongoose.Schema({ title : { type: String, required: true }, body : { type: String, default: '' }, coun ...

Navigate through a list of data in JSON format

After successfully implementing a jQuery AJAX call, I encountered difficulty in parsing the returned value. Working with a MySQL database, I am returning a PHP array() to my jQuery AJAX function using echo json_encode($reservationArray); Upon appending th ...

Using React Native, you can easily apply styles to View components by passing them

Is it a bug? Or is the View styles props object supporting inline props as well? For example, in the traditional way and also written in React Native documentation: function App() { return ( <View style={styles.box}></View> ) } const ...

Unable to establish communication with server. Facing issues in connecting AngularJS with NodeJS

I am currently working on establishing a communication process between my server and client to receive either a "success" or "failure" response. The server is being developed using node.js with the express framework, while the client is built using angular ...

The mysterious plugin "transform-runtime" has been detected in the ".babelrc" file located in "UsersPhpstormProjectseasy-essay"

After downloading a GitHub repository, I came across a file named .babelrc.json with the following contents: { "presets": [ "es2015", "stage-0" ], "plugins": [ "transform-runtime", "add-module-exports", "transform-decorators-lega ...

Utilizing Selenium and JavaScript to discover and extract the subject fields within a table

In my sent message list, I am trying to display the subject fields of all messages using Selenium and JavaScript (not Java) for coding. Here is the code snippet: <table class="messages"> <tbody><tr class="section-heading"> < ...

Performing bulk operations on multiple documents in MongoDB by specifying a custom identifier for updating or

Recently, I've been working with a mongo schema const taskSchema=new Schema({ userID:{type:ObjectId,required:true}, task: { type: String, required: true, trim: true, maxlength: 30, }, finalDate:{type:Date,required:true}, ...

Using JavaScript to automate keystrokes programmatically

Is there a way to programmatically close a webpage using the keyboard shortcut control + W? I'm wondering if I can write code that will mimic this specific shortcut (control+W). ...

Nested mapping of objects in a mapped object

I'm attempting to iterate through an array within another array that has already been iterated My objective is to display the userName and products each user has. To achieve this, I first map the main data array to show the userName of each object. ...