Page Performance Issue with Countdown in Angular on Component Reload

Discussão em 'Angular' iniciado por mohammad harris, Janeiro 3, 2025.

  1. I'm developing an Angular app where I fetch a list of coupons from an API. Each coupon has a countdown timer showing the remaining time until it expires. However, I am facing performance issues when trying to display this countdown. When I trigger the countdown update every second using the interval() function in ngOnInit, the page fails to load properly after navigating between pages or reloading the component.

    import { Component, inject, OnDestroy } from '@angular/core';
    import { HttpService } from '../../services/http.service';
    import { CommonModule } from '@angular/common';
    import dayjs from 'dayjs';
    import duration from 'dayjs/plugin/duration';
    import { interval, Subscription } from 'rxjs';

    dayjs.extend(duration);

    @Component({
    selector: 'app-offers',
    standalone: true,
    imports: [CommonModule],
    templateUrl: './offers.component.html',
    styleUrls: ['./offers.component.scss'],
    })
    export class OffersComponent implements OnDestroy {
    http = inject(HttpService);
    coupons: any[] = [];
    countdownSubscription: Subscription | null = null;

    ngOnInit(): void {
    console.log('ngOnInit called');
    this.getCoupons();
    }

    ngOnDestroy(): void {
    if (this.countdownSubscription) {
    this.countdownSubscription.unsubscribe();
    console.log('Countdown subscription cleaned up');
    }
    }

    getCoupons() {
    this.http.get2('coupon', false).subscribe({
    next: (res: any) => {
    console.log('Coupons received:', res);
    this.coupons = res.map((coupon: any) => ({
    ...coupon,
    timeLeft: this.calculateTimeLeft(coupon.startTime, coupon.endTime),
    }));
    console.log('Coupons with time left:', this.coupons);

    this.startCountdown();
    },
    error: (err) => {
    console.error('Error:', err);
    },
    });
    }

    startCountdown() {
    this.countdownSubscription = interval(1000).subscribe(() => {
    this.updateCountdown();
    });
    }

    calculateTimeLeft(startTime: string, endTime: string) {
    const now = dayjs();
    const end = dayjs(endTime);

    if (now.isBefore(dayjs(startTime))) {
    return 'Coupon not started yet';
    }

    if (now.isAfter(end)) {
    return {
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0,
    };
    }

    const duration = dayjs.duration(end.diff(now));
    return {
    days: duration.days(),
    hours: duration.hours(),
    minutes: duration.minutes(),
    seconds: duration.seconds(),
    };
    }

    updateCountdown() {
    console.log('Updating countdown...');
    this.coupons.forEach((coupon) => {
    coupon.timeLeft = this.calculateTimeLeft(coupon.startTime, coupon.endTime);
    });
    }
    }



    How can I optimize this logic to ensure that the countdown works properly, the page loads quickly, and it doesn't cause performance issues when navigating away from or reloading the component? Is there a better way to handle intervals in Angular for this type of dynamic timer without affecting page performance?

    Continue reading...

Compartilhe esta Página