YourReflection
YourReflection

Reputation: 395

Call another function after timeout is reached

I have the following code in JavaScript which I'd like to convert to TypeScript:

testJS(): void {
 $timeout(function () {
  this.done = true;
 }, 1).then(function () {
  $timeout(function () {
   this.done = false;                        
  }, 1000);
});              
}

I am trying to use the setTimeout function in TypeScript but I am not quite sure how to solve the ".then" part. Can anyone help me on this? The code so far:

testTS(): void {
 setTimeout(function () {
  this.done = true;
 }, 1).then(function () {
  setTimeout(function () {
   this.done = false;                        
  }, 1000);
});              
}

Upvotes: 1

Views: 248

Answers (1)

Paleo
Paleo

Reputation: 23702

Step 1: Make a promise using setTimeout

function wait(ms: number): Promise<void> {
    return new Promise<void>(resolve => setTimeout(resolve, ms))
}

Step 2: Use the promises

function testJS(): void {
    wait(1).then(() => {
        this.done = true;
        return wait(1000)
    }).then(() => {
        this.done = false;   
    })
}

Step 2 (alternative): await the promises

async function testJS2(): Promise<void> {
    await wait(1)
    this.done = true;
    await wait(1000)
    this.done = false;   
}

Notice: The this binding in unclear in your example.

Upvotes: 1

Related Questions