Using Vue.js to dynamically calculate elapsed time

I am attempting to display the changing elapsed time from a specified start time

<template>
  <div class="dashboard-editor-container">

      <div class="wrapper__body">

          <el-row :gutter="30">
             <el-col v-for="item in options" :key="item.value" align="middle" :xs="24" :sm="24" :md="24" :lg="4" :xl="24" style="margin-bottom:10px">

                 <el-button type="primary"  style="width: 180px;height:120px ;"  >{{item.label}} - {{getTimer(item.FechaHora)}}</el-button>
             </el-col>

          </el-row>


      </div>



  </div>
</template>

js

 <script>
    export default {
      data() {


       return {
            options: [{
              value: '01',
              label: 'Room 1',
              FechaHoraInicio:'2020-02-18T18:17:53.56',
              FechaHoraSalida:'2020-02-18T18:17:53.56',
            }, {
              value: '02',
              label: 'Room 2',
              FechaHoraStartTime:'2020-02-18T18:17:53.56',
              FechaHoraSalida:'2020-02-18T18:17:53.56',
            }, {
              value: '03',
              label: 'Room 3',
              FechaHoraStartTime:'2020-02-18T18:17:53.56',
              FechaHoraSalida:'2020-02-18T18:17:53.56',
            },
    }
    }
    },
 computed: {

    getTimer : function(FechaHoraInicio) {

       setInterval(function(){ 
           return  Date.now()-new Date(FechaHoraInicio)
       }, 3000);

    },
  },
    }

    </script>

The buttons are generated dynamically with individual start times, and I aim to calculate the passing time dynamically

For each button created dynamically with its specific start time, I require the dynamic display of elapsed time as a clock by subtracting the current time from the start time.

https://i.stack.imgur.com/QXIGt.png

The displayed time indicates the duration since the room was rented

Answer №1

Hopefully, this solution will be helpful for you:

new Vue({
  el: "#app",
  data() {
    return {
      options: [
        {
          value: "01",
          label: "Room 1",
          FechaHoraStartTime: "2020-02-18T18:17:53.56",
          FechaHoraSalida: "2020-02-18T18:17:53.56"
        },
        {
          value: "02",
          label: "Room 2",
          FechaHoraStartTime: "2020-02-18T18:17:53.56",
          FechaHoraSalida: "2020-02-18T18:17:53.56"
        },
        {
          value: "03",
          label: "Room 2",
          FechaHoraStartTime: "2020-02-18T18:17:53.56",
          FechaHoraSalida: "2020-02-18T18:17:53.56"
        }
      ],
      intervalEvents: []
    };
  },

  created() {
    this.setTimers();
  },
  
  beforeDestroy() {
    this.intervalEvents.map(intervalEvent => {
      clearInterval(intervalEvent)
    })
  },

  methods: {
    setTimers() {
      this.options = this.options.map(option => ({
        ...option,
        elapsed: "",
        startTimeAsDate: new Date(option.FechaHoraStartTime)
      }));

      this.options.map(option => {
        const event = setInterval(() => {
          option.elapsed = new Date(new Date().getTime() - option.startTimeAsDate).toLocaleTimeString();
        }, 1000);
        
        this.intervalEvents.push(event)
      });
    }
  }
});
<link
  rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>

<div id="app">
  <div class="dashboard-editor-container">
    <div class="wrapper__body">
      <el-row :gutter="30">
        <el-col
          v-for="(option, index) in options"
          :key="index"
          align="middle"
          :xs="24" :sm="24" :md="24" :lg="4" :xl="24"
          style="margin-bottom:10px"
        >
          <el-button type="primary" style="width:180px;height:120px ;">
          {{option.label}} {{ option.elapsed }}
          </el-button>
        </el-col>
      </el-row>
    </div>
  </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

Need some assistance in finding a way to input multiple values from multiple buttons into a single input field in JavaScript

Hello, I am looking for a little help with reading multiple values using multiple buttons such as 1, 2, and 3, and displaying the output in the input like '123' instead of just one number at a time. Concatenate numbers with every click. <inpu ...

Accessing the element within an ion-tab using document.getElementById

Within my ion-view, I have ion-tabs containing a canvas element. However, when attempting to retrieve the canvas using document.getElementById('photoCanvas'); I receive 'undefined'. Here is the code snippet: HTML: <ion-view ...

What could be causing the HTML content to not display when the code is executed?

I've recently started using Visual Studio Code for my project. I am able to build my code without any errors, but when I run it, the HTML content does not display properly - only the CSS styling for the header and footer is visible. I have tried click ...

Accessing a specific element within an array that has been nested within another array, using JavaScript

Here's what my code looks like: planets[0]= new THREE.Mesh( geometry, material ); planettexts[0]= new THREE.Mesh( textGeometry, textMaterial ); planets[0].add(planettexts[0]); Now, I am trying to hide the planettext, but every attempt results in an ...

What is the best way to implement an automatic logout feature in PHP?

I develop websites with login/logout functionality. Whenever a link or button is clicked on the website, I use an ajax function to verify the user's login status and automatically log them out if their session has expired. The logout function also up ...

Ensuring the validation of JSON schemas with dynamically generated keys using Typescript

I have a directory called 'schemas' that holds various JSON files containing different schemas. For instance, /schemas/banana-schema.json { "$schema": "http://json-schema.org/draft-06/schema", "type": "object", "properties": { "banan ...

The setState function in React Native seems to be having trouble updating

I've been attempting to access state from a component, but for some reason, I'm not seeing any changes when I use setState(). Here is the current state of my component: class MyTestComponent extends React.Component { constructor(props){ ...

Unlocking the potential of GraphQL: Harnessing the power of sibling resolvers to access output from another

Could use a little assistance. Let's say I'm trying to retrieve the following data: { parent { obj1 { value1 } obj2 { value2 } } } Now, I need the result of value2 in the value1 resolver for calculation ...

Tips for validating forms using jQuery

Upon form submission, an alert is displayed before redirecting to a new page. I have implemented a function that triggers on button click. The alert will appear first, followed by the form submission. I would appreciate ideas on how to validate the form. ...

The email field was blank when attempting to log in using Google authentication on Firebase

I encountered an issue where the email was null when using Firebase Google login. Below is the code I tested: function googleSignIn() { var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithPopup(provider) .then(fu ...

Engage with React JS arrays of objects

I have a specific object structure that looks like the following: [ { "periodname": "Test", "periodtime": "" }, { "periodname": "", "periodtime&quo ...

Issue: Error occurs when using _.sample on an array containing nested arrays

I am working with an array of arrays that looks like this: [[0,0], [0,1], [0,2], [0,3]...] My goal is to randomly select N elements from the array using Underscore's _.sample method: exampleArr = [[0,0], [0,1], [0,2], [0,3]...] _.sample(exampleArr, ...

What is the most effective way to programmatically select checkboxes based on array values in

Trying to keep it concise :) Working on a project that generates multiple pages of thumbnail images with checkboxes. The total thumbnails vary and are sorted into 1000 item html pages, called by a parent html page via iframe. Goal is for users to check che ...

Utilize identical portions of Vue template across multiple instances

Is it possible to reuse the same part of a template in multiple locations without duplicating code? I know that in JSX, I can encapsulate the repeated template portion within a function and then render that function wherever needed. But is this also possib ...

When trying to use setInterval () after using clearInterval () within an onclick event, the functionality seems

Can anyone assist me with an issue I am encountering while using the setInterval() function and then trying to clear it with clearInterval()? The clearInterval() works fine, but the automatic functionality of li elements with a specific class suddenly stop ...

I am having trouble getting Vue.js to function properly within HTML when using Django. Can someone please lend me a

The code run Here is the HTML document: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> <!--javascript extensions--> <script src=' ...

Using Javascript's .replace() method to preserve HTML elements

This is a JavaScript function I wrote function replaceCharacters(text_input){ return text_input .replace(/O/g, 0) .replace(/I/g, 1) .replace(/o/g, 0) .replace(/i/g, 1) .replace(/t/g, 4) .replace(/d/g, 9) ...

Tracking changes in real time and calculating the sum with AJAX, PHP, and MySQL for efficient processing

Initially, I kindly request you to read this until the end. I am in dire need of assistance with my problem as I have searched for solutions but still remain clueless. Referring to the image provided, the first 'Product & Total Product' element ...

Manipulate Angular tabs by utilizing dropdown selection

In my latest project, I have developed a tab component that allows users to add multiple tabs. Each tab contains specific information that is displayed when the tab header is clicked. So far, this functionality is working perfectly without any issues. Now ...

What is the best way to search using vuefire?

import { collection, limit, query } from "firebase/firestore" import { useFirestore, useCollection } from "vuefire" const db = useFirestore() const messagesRef = collection(db, 'rooms/1/messages') const messages = useCollect ...