简体   繁体   中英

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]);
...

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.

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);

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();
   }
}

You can try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM