0

could only find JS stuff on this. I just have basic functions that reload page elements and I want to delay them by like 1-2 seconds to wait for http calls to come through. I tried this (imported from rxjs to) but it doesn't work at all

    setTimeout(function () {
      this.clearGroups();
      this.prepareRow();
      this.prepareGroups(); 
    }, 2000);
3
  • 3
    "to wait for http calls to come through." You should probably be using promises and async/await to ensure these are called after the reload. Otherwise, you get into a dangerous territory when the calls might be out of sync. Commented Mar 26, 2021 at 7:11
  • 1
    But if you do want to use setTimeout, you need an arrow function, otherwise the value of this will be incorrect. Commented Mar 26, 2021 at 7:11
  • 3
    You don't want to wait for HTTP calls to come through using setTimeout(). There is a reason HTTP calls are asynchronous. Because you don't know when they will respond. If you're using Angular HttpClient to make the calls, then you need to place the statements that depend on it inside the subscription. If there are multiple independent calls, use forkJoin to combine them. If they are dependent on each other, map them using switchMap. Commented Mar 26, 2021 at 7:15

1 Answer 1

8

As @VLAZ points out, you need a arrow function (to "close over" the correct this-scope, eg.:

setTimeout(() => {
   this.clearGroups();
   this.prepareRow();
   this.prepareGroups(); 
}, 2000);

I would however suggest that you reconsider your solution, what about the users that has very poor internet connectivity, where the result could take more than 2 seconds "to arrive", and do you want to penalize people with a fast connection to wait the 2 seconds (for the update to appear)?

If your data arrives as a promise, consider using async / await:

await getData();
this.clearGroups();
this.prepareRow();
this.prepareGroups(); 

(please notice that this will only work if done from an async function, else use as traditional Promise with .then(() => ...))

or as an Observable:

getData().pipe(first()).subscribe(() => {
   this.clearGroups();
   this.prepareRow();
   this.prepareGroups(); 
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much @Anders, I did solve it with setTimeout however I kep thinking of it and would be super curious of a better solution so I asked another question and would immensely appreciate if you could review it real quick. Thanks. stackoverflow.com/questions/66852659/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.