Angular 7 features a table with multiple timers indicating the remaining time until expiration

I have a table with multiple rows where I need to display a timer showing the remaining time in days, hours, minutes, and seconds.

After researching how to calculate the remaining time using this link, I found a solution that works well. I am calling the same function in a column using {{myXYZFunction()}} and it is accurately calculating the date and time as expected.

However, I have noticed that sometimes the function call lags, resulting in seconds updating after 2 seconds instead of smoothly transitioning from 1 to 60. The sequence seems irregular like 1,2,4,6,8,10,12,13,14,15,17... 60 rather than a consistent update every second.

Answer №1

When it comes to performance, it is best practice to avoid having function calls directly in the template as they are executed every change detection cycle. To improve this, consider updating a member variable with the desired values before displaying them.

@Component({
  selector: 'app-component',
  template: '
    <table>
      <thead>
        <tr>
          <th>Date</th>
          <th>Time left</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="time in times">
          <td>{{time.date}}</td>
          <td>{{time.counter | async}}</td>
        </tr>
      </tbody>
    </table>
  '
})
export class MyComponent {
  public times;

  constructor() {
    // Create an observable triggered every second.
    // Observable.interval(1000).subscribe(_ => this.time = myXYZFunction());
  }

  setupTimes() {
    const rawTimes = this.getTimes(); 
    this.times = [];
    rawTimes.forEach(tm => this.times.push({date: tm, counter: this.setupCounter(tm)});
  }

  setupCounter(time) {
    return Observable.interval(1000).pipe(map(_ => myXYZFunction(time)));
  }

  /**
  * Retrieve dates for display from the backend or use a static array.
  */
  getTimes(): number[]{
    return [];
  }
}

By controlling when your function is called, you can reduce unnecessary load and eliminate UI lag. It's important to note that displaying real-time data in a table may result in performance issues, so consider adjusting update intervals to minimize browser load.

UPDATE

The example has been updated to reflect displaying date and countdown timer in a table. Creating objects from these values aims to optimize performance, although frequent updates for multiple dates might still impact performance. Utilizing the async pipe eliminates the need for manual unsubscribing. For less demanding accuracy, consider increasing the interval between counters to reduce browser strain.

setupCounter(time) { // Updated every minute.
  return Observable.interval(60000).pipe(map(_ => myXYZFunction(time)));
}

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 dynamically resizing a div element as a user scrolls, allowing it to expand and contract based on

I was working on a project and everything seemed easy until I hit a roadblock. What I am trying to achieve is expanding a div to 100% when scrolling down to the bottom of the div, then shrink it back to 90% at the bottom and do the reverse when scrolling ...

How to make an entire video clickable on Android for seamless playback?

I have implemented an HTML5 video in my mobile web application. Currently, users need to click the small play icon at the bottom left of the video to start playing it. Is there a way to make the entire video clickable so it plays when clicked anywhere on t ...

Tips for showing various images from a server using ng-repeat

Is it possible to display different images from a server using AngularJS? I have ng-repeat set up for posts and for each post, I want to retrieve its avatar. My approach is to call a function getImage(post.author.id) to fetch the corresponding avatar. $ ...

The result of calling addEventListener is undefined

My issue lies with the addEventListener function, as it is not working correctly. I've created a function that requires an event listener to track scrolling and then execute a callback function. window.addEventListener("scroll", checkPosition); Unf ...

Are you interested in removing a user account?

As a newcomer, I'm attempting to delete a profile but keep encountering this message in the address bar: http://thexyz.com/the/delete.php?id=1> I'm wondering if I've made a syntax error in my code below- <?php $i=1; while( ...

Prevent CSS3 columns from reverting back to their original state after being rendered

Utilizing css3 columns, I have created a layout with an unordered list displayed in 3 columns. Each list item contains another list that can be toggled to show or hide by clicking on the title using jQuery. The structure of the html is as follows (with ex ...

Merge identical data into a unified field within a table

I have a table that displays different colors and their quantities. I would like to merge rows with the same color into one row, with the total quantity shown in that row. For instance, if there are 2 "black" colors with quantities of 5 and 2, I want to c ...

Adding information to a database by utilizing Jquery, Ajax, and PHP

Trying to use ajax to submit data to a database has been a challenge for me. Even with a simple code test, I can't seem to make it work. Here is the HTML/ajax code snippet: <?php include("osb.php");?> <script type = "text ...

Calculating the number of digits in a series of numbers, experiencing a timeout issue (What is the page count of a book? from codewars)

Solving the Digits in a Book Problem Find the number of pages in a book based on its summary. For example, if the input summary is 25, then the output should be n=17. This means that the numbers 1 to 17 have a total of 25 digits: 123456789101112131415161 ...

Error: Failed to find the location because geolocate has not been defined

I searched extensively online for a solution to my problem without success, so I am reaching out to seek your assistance. I am attempting to utilize the Google Address auto-complete API within an asp.net core framework. In my razor file, I have included: ...

Error encountered when attempting to include a foreign key

I am attempting to establish a 1:1 relationship between two tables. The RefreshToken table will contain two foreign keys connected to the Users table, which can be seen in this image: https://i.stack.imgur.com/B2fcU.png To generate my sequelize models, I ...

What is the best way to dynamically convert a lodash object (specifically a filter object) into jQuery's listview component?

After referencing the answer to this topic as my first step, which can be found here, my next goal is to utilize a filter function to retrieve all matching entries from a JSON file based on a search term. The objective is to loop through each match and con ...

Issues with JavaScript and CSS functionality not functioning correctly as expected

There seems to be an issue with the order of HTML elements in the following code. When I place the div with the class thumb-bar before the full-img div, the JavaScript functions correctly. However, if I switch their positions, the JavaScript functionalitie ...

The server will only load on Safari's localhost and not on Chrome's

My Node server is only working in Safari when using http://localhost:8000, but not in Chrome. Interestingly, using 127.0.0.1:8000 works on both browsers. I'm puzzled as to why localhost doesn't work in Chrome even though pinging localhost in my t ...

I'm having trouble figuring out why this React Router setup is not functioning properly. Can anyone provide any insights

As I delve into react routing practice, I've put together a geography-based web app. Starting off, I configured the router paths: import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { BrowserRo ...

Link several jQuery elements to a function simultaneously

Having 3 jQuery objects is my current situation: var first = $('.el1'); var second = $('.el2'); var third = $('.el3'); I am trying to attach a "change" event to all of them simultaneously, but facing some challenges :( $(fi ...

Moving the starting directory of a NodeJS application on Azure

My NodeJS app on Azure was initially written in Javascript with the app.js file located in the root directory. This file was automatically detected during deployment via Git. Recently, I converted the app to Typescript and now have a build directory, with ...

Is it possible to include multiple eventTypes in a single function call?

I have created a function in my service which looks like this: public refresh(area: string) { this.eventEmitter.emit({ area }); } The area parameter is used to update all child components when triggered by a click event in the parent. // Child Comp ...

The JavaScript function getSelection is malfunctioning, whereas getElementById is functioning perfectly

I am encountering a peculiar situation while trying to input text into a textbox using a JavaScript command. The CSS locator does not seem to update the text, whereas the ID locator is able to do so. URL: Below are screenshots of the browser console disp ...

Dealing with side effects in react/redux: Best practices and tips

Trying to find the best way to integrate an async side-effects handler into my react/redux setup has been quite a challenge. In my react-router-driven application, all the main containers at root level are smoothly dispatching actions and receiving update ...