Auto refreshing a web page programmatically could be tricky for most newbie developers and today, I am going to share my approach on this. There are 2 possible solutions to auto refresh a web page.
For the HTML auto refresh solution, we will make use of meta element with http-equiv and content attributes. We simply need to set refresh as the value of http-equiv attribute. Also, we want to auto refresh the web page every 5 seconds and for that reason, we will set 5 as the value of the content attribute.
In the following example, we will cover both the solution mentioned above. We will simply display a counter of 5 seconds on the screen and as soon as it completes, the auto refresh will be triggered. Please have a look over the code example and the steps given below.
HTML & CSS
We have an h1 element in the HTML file. It contains style attribute to center align the text content.
HTML Auto Refresh
We have added a meta element with http-equiv and content attributes in the head element.
The value of http-equiv is set to refresh. It will help us in refreshing the page.
The value of the content attribute is set to 5 and this means that wait for 5 seconds before refreshing the page.
We have one global variable count and that holds a value of 1.
We are using the setInterval() method with a delay of 1 second. It will take an anonymous method as its first parameter which will be executed after each interval of 1 second.
In the anonymous method, we have selected the h1 element using the document.querySelector() method. We are setting the current value of the count variable as innerText of h1 element and incrementing the value of count by 1.
We are using the if statement to verify whether the count has reached number 5 or not. If yes, we are going to make use of reload() method of location object to trigger an auto refresh.