Implementing countdown in angular causes browser to load infinitely

Discussão em 'Angular' iniciado por Sachin Kizhakkepurath, Janeiro 24, 2025.

  1. Im calculating the time remaining for an auction using the auction_end_time property. But when i try to update the time using rxjs interval or any other operators, the browser is not displaying anything.


    ngOnInit(): void {
    for (let i = 0; i < this.futureProducts.length; i += 4) {
    this.groupedFutureAuctions.push(this.futureProducts.slice(i, i + 4));
    }

    this.responsiveOptions = [
    {
    breakpoint: '1199px',
    numVisible: 1,
    numScroll: 1,
    },
    {
    breakpoint: '991px',
    numVisible: 2,
    numScroll: 1,
    },
    {
    breakpoint: '767px',
    numVisible: 1,
    numScroll: 1,
    },
    ];
    this.fetchLiveAuctions();
    }

    ngOnDestroy(): void {
    this.stopCountdown();
    }

    fetchLiveAuctions(): void {
    this.auctionService
    .getLiveAuctions()
    .then((result: any) => {
    if (result?.data) {
    console.log('Result in fetch live auctions', result.data);

    // Properly map the auctions and add time remaining
    this.liveAuctions = result.data.map((auction: Auction) => ({
    ...auction,
    timeRemaining: this.calculateTimeRemaining(
    auction.auction_end_date
    ),
    }));

    // Start the countdown after fetching auctions
    this.startCountdown();
    }
    })
    .catch((error) => {
    console.error('Error fetching live auctions:', error);
    });
    }

    startCountdown(): void {
    // Stop any existing countdown
    this.stopCountdown();

    // Start a new countdown that updates every second
    this.countdownSubscription = interval(1000).subscribe(() => {
    this.liveAuctions = this.liveAuctions.map((auction) => ({
    ...auction,
    timeRemaining: this.calculateTimeRemaining(auction.auction_end_date),
    }));
    });
    }

    stopCountdown(): void {
    if (this.countdownSubscription) {
    this.countdownSubscription.unsubscribe();
    this.countdownSubscription = null;
    }
    }

    calculateTimeRemaining(endDate: string): string {
    if (!endDate) return 'Invalid date';

    const end = new Date(endDate).getTime();
    if (isNaN(end)) return 'Invalid date';

    const now = Date.now();
    const diff = end - now;

    if (diff <= 0) return 'Auction ended';

    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);

    return `${days}D ${hours}H ${minutes}M ${seconds}S`;
    }

    the browser will stop loading once i comment the startCountdown function, but whenever i try to update the time remaining in real time, the browser keeps on spinning around

    Continue reading...

Compartilhe esta Página