Automatically refresh a page every N seconds in JavaScript
In this tutorial we are going to learn how to automatically refresh a page in every N seconds using the JavaScript.
Using the setTimeout and location.reload method
To refresh a page automatically in every N seconds, we need use the combination of setTimeout() function and location.reload() method.
The setTimeout()
function is used to run a function or a piece of code after a specified amount of time is completed.
The location.reload() method helps us to refresh or reload a current webpage just like how browser reload button does the refresh.
The location.reload()
method also accepts a optional argument boolean, if we pass true
the page will be reloaded from the server. if we pass false
or unspecified the page will be reloaded from the browser cache.
Here is an example, that refreshes the page automatically in every 5 seconds:
setTimeout(() => {
location.reload()
}, 5000);
In the above code, we have passed the two arguments to the setTimeout() function. The first argument is the function that runs after a specific amount of time. The second argument is the 5000 milliseconds (or 5 seconds). So the setTimeout function runs the location.reload() once a 5 seconds timer is completed.
After a page refresh the setTimeout() function Re-initializes again the new timer for 5 seconds like that it refreshes the page automatically in every 5 seconds.
Using http-equiv meta tag to refresh a page in every n seconds
If you don’t like using the JavaScript way we can also use the http-equiv meta tag that refreshes a page automatically in every N seconds.
Here is an example, that refreshes a page in every 10 seconds:
<head>
<!-- refreshes the page in every 10 seconds -->
<meta http-equiv="refresh" content="10"/>
<head>
In the above example, we have passed the value refresh
to the http-equiv attribute. So it tells the browser to refresh or reload a page after a specified time in the content attribute, in our case the timer for 10 seconds.