1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Interval function causes infinite UI load unless I type in "/index.html" in the URL

Discussão em 'Angular' iniciado por blueberrybun, Setembro 11, 2024.

  1. blueberrybun

    blueberrybun Guest

    I'm trying to make a simple digital clock in my Angular app, but currently I'm just having it display a counter while I figure out what the heck is going on:

    In clock.component.html:

    <div class="time" id="time">{{ secondsPassed }}</div>


    In clock.component.ts:

    @Component({
    selector: 'app-clock',
    standalone: true,
    imports: [],
    templateUrl: './clock.component.html',
    styleUrl: './clock.component.scss'
    })
    export class ClockComponent implements OnInit, OnDestroy {

    secondsPassed: number;
    timer: any;

    constructor() {
    this.secondsPassed = 0;
    }

    ngOnInit(): void {
    this.startTimer();
    }

    ngOnDestroy(): void {
    if (this.timer) {
    clearInterval(this.timer);
    }
    }

    startTimer() {
    this.timer = setInterval(() => {
    this.secondsPassed++;
    console.log(this.secondsPassed);
    }, 1000)
    }
    }


    Whenever I do ng serve and go on localhost:4200, it will forever be stuck on the spinning loading circle unless I manually type in localhost:4200/index.html, at which point it will display the timer correctly and update.

    I tried a bunch of different things, including rxjs subscription and async pipe, but nothing worked. I even tried running outside the Angular zone, but with that the timer doesn't update.

    One really weird thing I noticed is that whenever I save changes to my code and it rebuilds while the Angular local server is running, it will appear as if there are two timers running, so I'm not sure if ngOnDestroy is called and the first one isn't cleared? I am pretty new to Angular so I don't know if this has anything to do with my issue.

    Thanks for your help!

    Continue reading...

Compartilhe esta Página