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

Assign specific CSS classes to elements based on the v-model value in Vue.js

Looking to create a dynamic table using Vue and trying to add a class to a row when a checkbox is checked. Each checkbox is associated with a specific value in an object of objects. View the code on Codepen. <tbody> <tr v-for="row in filter ...

A step-by-step guide on executing a callback function once the animation has finished with frame-motion

I'm facing an issue with my component called AnimatedText. After the animation is complete, I want the words filled in the underlineLines prop to be underlined. How can I achieve this? I attempted using the onAnimationEnd function, but it didn't ...

JS Month Interval Bug Causing Issues with Chart Date

This script retrieves and summarizes download data from MySQL by day, displaying it as a chart. However, there's an issue with the way dates are handled between PHP and JavaScript (Highcharts). While PHP outputs month values from 1 to 12, JavaScript c ...

Tips for personalizing Twitter Bootstrap popover concealment animation

Currently, I am interested in creating a unique hide animation for my popover. Instead of directly modifying bootstrap.js, I would like to implement my own custom code. $.fn.popover = function (option) { return this.each(function () { ...

Navigate to a particular date with react-big-calendar

I know this might sound like a silly question, but I am new to working with React. Currently, the React-big-calendar allows users to navigate to specific dates when selected from the Month view. What I want is for the same functionality to apply when a use ...

Error message: Error in jQuery: Object is required for Internet

I have a button that is designed to trigger the opening of a jQuery UI Dialog when clicked. Strangely, it works perfectly in FF3, FF4, Chrome, and IE8 with ChromeFrame, but fails to function in regular IE8. The error message displayed simply states "Object ...

Transferring data between functions within the same controller in AngularJS

I have implemented two functions to handle the timing of a process, one for starting and one for stopping. Here is the code snippet: $scope.start = function(data) { $scope.time = { id: '', mainId: data.id, start: &ap ...

Vue.js and Laravel-Vue.js seem to have trouble detecting updates in their components

Just started diving into Vue.js while working with Laravel. Everything seems to be running smoothly and my components are showing up just fine. However, I noticed that whenever I refresh the page, I lose all the changes. How can I make sure that these chan ...

Guide to populating a full calendar using JSON information

Implementing the FUllCALENDAR CSS template for creating a meeting calendar has been my current project. The servlet class I am using is CalendarController. However, when running it, the output appears as follows: {"events":[{"id":1,"title":"1","s ...

Retrieve JSON object based on its unique identifier from a different JSON file

I am working with 2 API resources: and it returns JSON data like this: { "id": 771, "title": "Call to Alyce Herman - Engine Assembler", "assigned_with_person_id": 317, } provides ...

Throw an error if the entry is not found in the Firebase database

I have an array containing various objects. Users should be able to access all objects using moduls/, and a specific one with moduls/$id. However, if the requested modul does not exist, the database should return an error to inform the client that there is ...

Can WikiData be accessed by providing a random pageId?

My current project involves creating a Wikipedia Search App with a 'Feel Lucky' button. I have been trying to figure out if it's possible to send a request for Wikidata using a specific pageid, similar to the code below: async function lucky ...

Combining package.json commands for launching both an Express server and a Vue app

I recently developed an application using Vue.js and express.js. As of now, I find myself having to open two separate terminal windows in order to run npm run serve in one and npm start in the other. My ultimate goal is to streamline this process and have ...

Guide to Saving a List in Local Storage

I have successfully created a CRUD page where users can input text and it gets added to a list. Now, I am trying to save that list in localStorage but encountering an issue where the console log is showing an empty object. Any assistance on this matter wou ...

The processing indicator fails to function properly when trying to refresh a jQuery datatable

I am currently customizing the loading indicator for the datatable using a spinner called startLoadGlobal(SPINNER_DATA_TABLE_FINANCEIRO_CARREGAR_REGISTROS) in jQuery. It works correctly when I initially load the datatable, however, when I reload it, the sp ...

Tips for causing the JavaScript confirm alert to appear just a single time

My latest project involves creating a confirm alert that notifies users when their password is about to expire, prompting them to change it. The functionality for this alert is located in the header section of the website. Upon successful login, users are ...

Using ngModel instead of value to bind a custom Angular directive for currency input

Currently, I am using a specialized mat-input-currency format directive to automatically convert my field inputs into currency. You can find the npm repository here. However, the directive binds the element data to [value] of the input, and I require it t ...

Animating scrollTop using jQuery is a useful feature for creating

I am facing an issue with several section tags within a div that has overflow set to hidden. The structure of the code is as follows: <div id="viewport"> <section> content </section> <section> content </ ...

Assistance with offsetting a jQuery drop down menu

This is the third jQuery script that I've been working on. While parts of it have been inspired by other scripts, I'm now focusing on implementing a specific feature. I've dedicated 4 hours to solving the issue of displaying the submenu on ...

Embracing JQuery for Frontend Development with Node.js

I'm currently enhancing my node.js skills by utilizing express, and I've encountered a situation that is causing me some confusion. Essentially, when a user requests a webpage and the backend sends them the HTML page, how can I incorporate a Java ...