Search code examples
javascriptangulartypescriptsettimeoutangular-changedetection

Angular 5 doesn't detect change during a long operation even if I use setTimeout


I am trying to show a ngx-bootstrap progress bar while my app is loading data from a csv file.

The Problem: The ui is frozen until the whole operation is over

I used setTimeout to split the loading and called it recursively. I also tried to call ngZone.run() and applicationRef.tick() and changeDetectorRef.markForCheck() ... without any success the progress bar only shows up full at the end of the operation.

I made a simpler stackblitz so you guys can show me how I can implement this. it's much simpler bcs in my code I put it in a service and I get the results through an observable. but if this works at least I would know what I'm doing wrong. https://stackblitz.com/edit/angular-gzdylf


Solution

  • In your example where you are using setTimeout to split up the work you are doing this:

    setTimeout(work());
    

    This means you are invoking the work function inside the loop instead of scheduling it to run later.

    You need to change it to pass the function reference to setTimeout to get it to work as expected:

    setTimeout(work);   // NOTE: `work` and not `work()`