Search code examples
angulartypescriptsettimeouttimedelay

How to delay execution of function in Angular/Typescript


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);

Solution

  • 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(); 
    });