Tuesday, January 7, 2020

TypeScript: sleep a thread

Hi All,

Today i am stuck in one functionality so using the thread in typescript i a solve it so thing share Knowledge to all people.

Sometimes you see within the second your method code is executed and you not understand how to stop our method so the simple idea is to use thread.

If we need to sleep e thread, we can implements a delay method that returns a Promise object (which represents the eventual completion, or failure, of an asynchronous operation, and its resulting value) and through the setTimeout method (that sets a timer which executes a function or specified piece of code once after the timer expires) resolve the Promise.

private delay(ms: number)
{
  return new Promise(resolve => setTimeout(resolve, ms));
}


Now we can call the delay method where we need to sleep the thread. To call the delay function we have to use the keyword await, so we must declare the method where we will make the call as async.

async downloadMyFile(id: number) {
    this.isLoadingSpring = true;
    const link = document.createElement('a');
    link.setAttribute('target', '_blank');
    link.setAttribute('href', '/assets/files/' + id + '/Year-Book.pdf');
    await link.setAttribute('download', 'Year-Book.pdf');
    document.body.appendChild(link);
    link.click();
    link.remove();
    await this.delay(3000);
    this.isLoadingSpring = false;
  }


Thank you for your valuable time hope it will help you 

No comments:

Post a Comment