I am curious about the behavior of JavaScript code, specifically related to the usage of setTimeout()
. When a user clicks on a link to navigate to another page, I wonder at what point the JavaScript code on the current page stops running and the code called by setTimeout will no longer execute. For example:
- Is it when the link is clicked (I know this is incorrect)?
- Is it when the browser begins loading the new page?
- Or is it at another point entirely?
Furthermore, I am interested to know if this behavior differs among the major web browsers.
Background Information
This question is purely out of curiosity, not to address a particular issue. The scenario that sparked my curiosity involves wanting to trigger an action when a user clicks on a specific link. Ideally, I would perform an ajax call and process the result, but completion before the page unloads is not a major concern. To explore this, I plan to use setTimeout() on the link click event, knowing that it may or may not finish before the page is unloaded. I am intrigued to learn the circumstances under which this approach may be successful. While there may be alternative solutions to this scenario, I am solely interested in understanding the behavior of JavaScript in this context.