Every Server sets a limit to the time it will wait for a reply, before closing the connection. This timeout is set in the cases you mentioned. Similarly if you are opened any site and dont do anything for long, your connection is timed out and you have to login.
The timeout is set by the web programmer. If a resources is not found, it will be searched untill connection times out.