最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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

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]);
...
Share Improve this question edited Aug 24, 2020 at 0:33 integral100x asked Nov 6, 2019 at 23:20 integral100xintegral100x 3426 gold badges21 silver badges51 bronze badges 3
  • just put the navigation line inside the setTimeout function – shuk Commented Nov 6, 2019 at 23:22
  • Try placing the navigation line inside of the timeout's callback function. – djfdev Commented Nov 6, 2019 at 23:23
  • Tried this and the answers below, but it doesn't seem to sleep for 5 seconds before navigating... – integral100x Commented Nov 7, 2019 at 15:34
Add a comment  | 

4 Answers 4

Reset to default 16

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

You can try this:

setTimeout(() => {
    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();
   }
}
发布评论

评论列表(0)

  1. 暂无评论