Issue
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]);
...
Solution
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:
- Cancel the timeout on route change; or
- Block the entire page to avoid clicking on any other route.
Answered By - Elias Soares
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.