In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.

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 methos where we will make the call as async.

private async sleepExample()
{ console.log("Before sleep: " + new Date().toString()); // Sleep thread for 3 seconds await this.delay(3000); console.log("After sleep: " + new Date().toString());

We can see that the console logs two date where the time differ of three seconds.

Laisser un commentaire