IvoL
IvoL

Reputation: 113

SetTimeout in Angular 8 is ignored

When running this code:

this.logger.warn('start');
setTimeout(() => {},3000);
delay(3000);
this.logger.warn('start2');

My output says this enter image description here

Blockquote: ngx-logger.js:596 2020-11-19T13:37:40.922Z WARN [10.js:10596] start Blockquote: ngx-logger.js:596 2020-11-19T13:37:40.925Z WARN [10.js:10602] start2

So basically my setTimeout gets ignored, same for delay(3000). What could be possible reasons for this? When I check with this.logger it is also ignored.

I am using Angular 8.

Upvotes: 1

Views: 9228

Answers (2)

user12688644
user12688644

Reputation:

The setTimeout() method works as asynchronous and it does not affect the running time in the main thread.

If you want to wait for some seconds, you can follow this answer. What is the JavaScript version of sleep()?

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two seconds later, showing sleep in a loop...');

  // Sleep in loop
  for (let i = 0; i < 5; i++) {
    if (i === 3)
      await sleep(2000);
    console.log(i);
  }
}

demo();

Upvotes: 1

Aditya Menon
Aditya Menon

Reputation: 774

The correct way to use setTimeout in your example would be like below:

this.logger.warn('start');
setTimeout(() => {this.logger.warn('start2')},3000);

delay is not a valid javascript function

Upvotes: 5

Related Questions