Find the variance between today's date and a selected date, then initiate the timer based on this variance

I have a grid containing data. I utilize the loadGrid() function to preload data or conditions before the grid finishes loading.

When the active state is set to 1, my intention is to initiate a timer by calculating the difference between the current date and the object's date (date.key.date) on this line.

In other words, if the time gap is 30 minutes... I want the timer to begin counting from 00:30:00...

The issue I'm facing is that the timer isn't starting, and I'm unable to pass its value to the fetchDisplay() service function.

Could someone offer assistance?

DEMO

Code:


data = [
    {
      id: 1,
      idUser: 1,
      name: "Name1",
      active: 1,
      date: "2020-02-01T20:00:00",
    },
    {
      id: 2,
      idUser: 2,
      name: "Name2",
      active: 0,
      date: "2020-02-01T20:00:00",
    },
    {
      id: 3,
      idUser: 3,
      name: "Name3",
      active: 0,
      date: "2020-02-01T20:00:00",
    }
  ];


  loadGrid(event) {
    if (event != null) {
      if (event.rowType !== "header") {
        if (event.data.decorrer === 1){
          this.interval = setInterval(() => {
            this.display = +this.datePipe.transform(Date.now(), 'yyyyMMddHHmmss') - +this.datePipe.transform(event.data.date, 'yyyyMMddHHmmss');
            // this.taskService.fetchDisplay() = this.display;
            return this.display;

          }, 1000);
        }
      }
    }
  }

  startTimer(data) {
    alert("start timer");
    this.currentRowIndex = data.id;
    let self = this;
    self.taskService.startTimer(data);
    self.currentState = self.taskService.getCurrentState();
  }

  pauseTimer(data) {
    alert("pause timer");
    let self = this;
    this.currentRowIndex = data.id;
    self.taskService.pauseTimer(data);
    self.currentState = self.taskService.getCurrentState();
  }

Answer №1

To calculate the time difference between the current date and a given date, you can use the setInterval function in JavaScript. First, parse the given date like this: Date.parse(data[0].date). Then, you can create a counter to update the display every second:

data = [
    {
      id: 1,
      idUser: 1,
      name: "Name1",
      active: 1,
      date: "2020-02-01T20:00:00",
    }
    ]
    
const date = Date.parse(data[0].date);  //the date of the object
const elem = document.getElementById('counter')

function count() {

  let countFrom = (Date.now() - date);//get the difference with the current date
  
  //convert to seconds, minutes and hours
  seconds = parseInt((countFrom/1000) % 60)
  minutes = parseInt((countFrom/(1000*60)) % 60)
  hours = parseInt((countFrom/(1000*60*60)) % 24);

  //append `0` infront if a single digit
  hours = (hours < 10) ? "0" + hours : hours;
  minutes = (minutes < 10) ? "0" + minutes : minutes;
  seconds = (seconds < 10) ? "0" + seconds : seconds;

  let time = `${hours}:${minutes}:${seconds}`;
  elem.textContent = time;
  
}

setInterval(count, 1000);
<div id='counter'></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

The compatibility between Typescript methods and event handlers is lacking

Consider this basic TypeScript script class foo { v: number = 1; public bar() { console.log(this.v); } } var a = new foo(); var b = new foo(); document.getElementById('test').addEventListener("click", a.bar); document.getE ...

Concealing the sidebar in React with the help of Ant Design

I want to create a sidebar that can be hidden by clicking an icon in the navigation bar without using classes. Although I may be approaching this incorrectly, I prefer to keep it simple. The error message I encountered is: (property) collapsed: boolean ...

Exploring JQuery techniques for iterating through numerous JSON files to create dynamic quizzes

Hi everyone, I could really use some assistance right now. I am working on developing a front-end system for a quiz, but I have encountered a challenge with the back-end. The back-end provides 3 JSON files to work with. JSON1 contains category and title in ...

Retrieve the value from another select element

Is there a way to create a function in pure JavaScript that changes the selected options in two select tags based on each other? For example, if I choose a French word in one select tag, the English equivalent automatically changes in the other select tag ...

How do I ensure that in Vue.js, the select element always has the first option selected even when other options are dynamically shown or hidden?

In my Vue app, I have a select element that dynamically shows or hides options based on the user's previous selections. For example: <select id='animal' v-model='values.animal.selected'> <option value='cat' ...

Variability in Focus Behavior while Opening a URL in a New Tab with window.open()

Here is a code snippet I have been using to open a URL in a new tab: window.open(urlToOpen, '_blank', 'noopener noreferrer'); The issue I am experiencing is that when this code is executed for the first time, it opens the URL in a new ...

When using the async pipe with Angular's ngFor, an error message indicates that the argument is

Can you explain why this error message is appearing: Argument of type '[string, { startTime: string; endTime: string; }][] | null' is not assignable to parameter of type 'Collection<unknown>'. It occurs when attempting to utilize ...

Ways to assign a default value to a radio button using a mock JSON dataset

As a beginner in AngularJS2, I am looking to resolve an issue where the checkbox is automatically checked when retrieving values from a mock JSON file. Can someone please help me? <div class="form-row"> <div class="formHeading">Skills *< ...

Creating a Nested DataTable: A Step-by-Step Guide

My data structure includes a nested dict presented as follows: var dataSet = [{"s_group": [{"range_name": null, "name": "XXXXXXXXXXXX"}], "configfile": "XXXXXXXXXXX", "src_port": ["0-65535"], ...

Can we move the "user" object to the forefront and retrieve it from a location other than the "on.AuthSateChanged(user => .... }" function?

Is there a way to define a ref in vuefire to firebase path that relies on the current User object? Can I bring the "user" object to the top level so it can be accessed outside the "on.AuthSateChanged(user => .... }" block? firebase-config.js import * ...

Can we create a collection of Vue highcharts components in a library format?

I am in search of an answer, with hope that it lies here. I have used the following: "vite": "^2.7.13", "highcharts": "^9.3.3", "highcharts-vue": "^1.4.0" I aim to create a library of Vue compon ...

Showing outcomes by making rapid consecutive AJAX requests

If you need a visual representation, I have a PHP script for a Hotel Management application that showcases a calendar (with columns representing days of the month and rows displaying prices per day). This script can be accessed in edit mode, where it gene ...

What could be causing this conflicting behavior with the logical "and" operator?

const {DEMO, PORT, LOCAL} = process.env; const socketAddress = (DEMO & LOCAL)? `http://${hostname}:${PORT}`: `wss://${hostname}`; When DEMO is false, PORT is undefined, and LOCAL is true The hostname being used is http://9f9cbf19.ngrok.io I verified ...

Exploring properties of nested elements in React

Picture a scenario where a specific element returns: <Component1> <Component2 name="It's my name"/> </Component1> Now, what I want to accomplish is something like this: <Component1 some_property={getComponent2'sN ...

The challenge of loading multiple objects asynchronously in three.js

When I try to load multiple models onto the same scene simultaneously, only one model is successfully loaded. For instance, if I have a building scene with various objects like chairs and toys inside, only one object gets loaded when I try to load them all ...

Is it possible to arrange a react map based on the length of strings?

I am working on a React function that loops through an object and creates buttons with text strings retrieved from the map. I want to display the text strings in order of their length. Below is the code snippet for the function that generates the buttons: ...

How can I effectively filter the data returned by consuming an API in JSON through an Angular service?

My Angular 6 project includes a UsersService that is injected into the UsersComponent. Originally, the component displayed mock data in the form of a string array. However, it now consumes JSON data from an API provided by JSONPlaceholder via the UsersSer ...

Crafting 3 intertwined combinations using the power of jQuery AJAX and PHP

Here's what I've been working on so far: The first page retrieves data and populates the first combobox, which is all good. Then, when users select a value from combo1, a second combobox is created with filtered data using AJAX - also working fin ...

`The Art of Binding() with Objects Created on the Fly`

Currently facing challenges with rebinding something using a dynamically created object from prepend. Despite trying several methods, I am only able to unbind. Seeking assistance. $(document).ready(function(){ $(".newdir").click(function(){ $(".d-exp ...

Extract information from the website "angular.callbacks" using web crawling techniques

Looking to utilize R for scraping news from the following URL: "AlphaGo"&ss=fn&start=0). Below is the code I am working with: url <- "http://api.foxnews.com/v1/content/search?q=%22AlphaGo%22&fields=date,description,title,url,image,type,taxo ...