Reputation: 342
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
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
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:
Upvotes: 16
Reputation: 313
You can try this:
setTimeout(() => {
this.router.navigate(['/question', this.getQuestionID() + 1]);
}, 5000);
Upvotes: 0
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