You can try to modify the displayed messages or the time provided to the
setTimeout function. Even with a
0 millesecond delay, the asynchronous message will be displayed after the synchronous message. This is because any function given to the
setTimeout function will be executed asynchronously, when the main thread is not busy anymore. You can try this code as an example:
What can we learn from this? Simply, never trust the delay given to the
setTimeout function. You can only specify a minimum delay. Even if you set a
0 delay, your code could be executed much later.
setInterval has the same behavior as
setTimeout but the code is executed multiple times. You have to call
clearInterval to kill the timer.
- Performing an HTTP request
- Any I/O operation when you are in a NodeJS environment
- Dealing with a WebSocket (client or server side)
The following code snippet is asynchronously reading a file with NodeJS: