Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does javascript stop running on a page after a link is clicked?

Tags:

javascript

I have a page which runs various javascript code, including calling setTimeout(). If a user clicks a link to navigate to another page, at what point does the javascript on this page stop running and therefore my code called by setTimeout will no longer be called? e.g.

  • as soon as the link is clicked (I know this is wrong)
  • when the browser starts receiving the new page
  • some other point?

And is this different for the different major browsers?

Background

I want to know this largely for interest's sake rather than to solve any particular problem. The problem which prompted me to think about this is I'd like to do something when a user clicks a particular link on a page. I want to perform an ajax call and process the result, but I'm not too concerned if it finishes before the page is unloaded. So I'll fire a setTimeout() on the link click and then if I'm lucky it'll finish but if I'm not it won't. I wondered in what circumstances it'll work. While there may be other solutions to that problem, I don't want solutions to the problem I only want to know the answer to the question.

like image 615
Rory Avatar asked May 08 '13 12:05

Rory


1 Answers

Here's the sequence of what happens:

Step 1: You click on a link. Here the browser sends a request to the server and waits for the response. The current page's document object still exists.

Step 2: Browser receives the response. The current page's document objects still exists.

Step 3: The browser parses, creates and renders the response to a new document object.

Step 3 is when the current page's JS will stop, UNLESS, you have targeted the response to an iframe, for example. If you do that, then the new document object will be rendered inside the iframe and the current page's document object remains intact and JS will still remain functional.

Hope that answers your question!

like image 110
om_deshpande Avatar answered Nov 09 '22 09:11

om_deshpande