Skip to content
Advertisement

settimeout not working properly when i tried to use it to refresh a page

The purpose of this code is to refresh a page after either a wait time of 1 second or 5 seconds depending on a random variable. However, the code below makes it so that it either refreshes after a wait time of 1 second EVERY SINGLE TIME, or it refreshes after a wait time of 5 seconds EVERY SINGLE TIME.

How do I make it so that the refresh wait time are EITHER 1 second OR 5 seconds on every refresh?

JavaScript

Advertisement

Answer

The issue is that while you are pointing the iframe to the current document, the document that contains the iframe is only being loaded once (and that’s why you are seeing the same interval being used over and over) and when the iframe loads the same file up inside of it, the value that it generates for interval is not the same one as is controlling the loading of the iframe.

I think you should just do an AJAX request for the current file inside of your setTimeout. That way you can handle a server error by just doing the AJAX call again. This would be way simpler. No iframe.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement