integral100x
integral100x

Reputation: 342

How do I make Angular sleep for 5 seconds before navigating to a new page?

Quick question, how do I make Angular sleep for 5 seconds before navigating to a new page?

I'm trying this inside my function but it doesn't seem to work:

setTimeout(() => {
        console.log('sleep');
      }, 5000);
this.router.navigate(['/question', this.getQuestionID() + 1]);
...

Upvotes: 9

Views: 28949

Answers (4)

Roman Šimík
Roman Šimík

Reputation: 900

If you want it written in the best way, you should use RXJS timer operator (documentation)

const subscription = timer(5000).subscribe(() => {
    this.router.navigate(['/question', this.getQuestionID() + 1]);
)};

also don't forget to unsubscribe in ngOnDestroy lifecycle hook (documentation)

ngOnDestroy() {
   if (this.subscription) {
       this.subscription.unsubscribe();
   }
}

Upvotes: 0

Elias Soares
Elias Soares

Reputation: 10254

This happens because setTimeout don't block code execution, instead it schedules a callback function execution. That said, your navigate call is outside the callback. This means that it will run right after the callback scheduling, not at it execution.

The right code is:

setTimeout(() => {
  console.log('sleep');
  this.router.navigate(['/question', this.getQuestionID() + 1]);
  // And any other code that should run only after 5s
}, 5000);

Note:

If user try to navigate away using some angular router link before tge 5s, it will still run the navigate after 5s causing an strange behavior.

You should neither:

  1. Cancel the timeout on route change; or
  2. Block the entire page to avoid clicking on any other route.

Upvotes: 16

Viktor Garba
Viktor Garba

Reputation: 313

You can try this:

setTimeout(() => {
    this.router.navigate(['/question', this.getQuestionID() + 1]);
}, 5000);

Upvotes: 0

AyushKatiyar
AyushKatiyar

Reputation: 1030

The code that is written inside the setTimeout(()=>{},5000) sleeps for 5 sec so try using

setTimeout(() => {
    console.log('sleep');
    this.router.navigate(['/question', this.getQuestionID() + 1]);
  }, 5000);

Upvotes: 0

Related Questions