2

How can I add a pause in this function, so that the value of 'datasum' changes every 2 seconds?

i:number; datasum:number; sum:number;
startCalculating(_i,_sum) 
{
 _i=1; _sum=0;
 while(_i<100)
 {
  _sum=_sum+2;
  this.datasum=_sum;
  _i=_i+1;
 }
}

I have already tried the methods suggested in: pausing-in-js, typescript-sleep and async/await-in-ts. Any help/suggestions would be greatly appreciated.

meeta
  • 33
  • 1
  • 8

1 Answers1

2

A solution could be to use the async/await pattern, and in your while loop you can await for a Promise that gets resolved after 2 seconds.

Something like this:

function delay(timeInMillis: number): Promise<void> {
  return new Promise((resolve) => setTimeout(() => resolve(), timeInMillis));
}

class YourClass {
  datasum = 0;

  async startCalculating(): Promise<void> {
    let _i = 0;
    let _sum = 0;
    while (_i < 100) {
      _sum += 2;
      this.datasum = _sum;
      await delay(2000);
      _i += 1;
    }
  }
}

For clarity, I tried to keep the code as similar as possible to your own.

Stefano Dalpiaz
  • 1,673
  • 10
  • 11