How to Automatic Refresh a web page in a fixed time?


We can auto-refresh a web page by either using a “meta” tag with the “http-equiv” property, or by using the setInterval() browser API. Automatic refreshing websites have certain use cases to them, for example, while creating a weather-finding web application, we may want to refresh our website after a set interval of time to show the user the near-exact weather data for a location.

Let’s look at the 2 approaches below to understand how to set up an auto-refreshing website.

Approach 1

In this approach, we will use the “http-equiv” property of a “meta” tag to refresh our web application after a particular interval of time which is passed in its “content” attribute. The meta tag is provided to us by default in the HTML5 specification.

Syntax

<meta http-equiv="refresh" content="n"> 

Here, “n” in a positive integer that refers to the number of seconds to refresh the page after.

Example

In this example, we will use the “http-equiv” property of a “meta” tag to refresh our web application after every 2 seconds.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>How to Automatic Refresh a web page in fixed time?</title>
   <meta http-equiv="refresh" content="2">
</head>
<body>
   <h3>How to Automatic Refresh a web page in fixed time?</h3>
</body>
</html>

Approach 2

In this approach, we will use the “setInterval()” API is given to us by the browser, which allows us to run a certain piece of code after every certain amount of time passed, both of which are passed as arguments to the browser API.

Syntax

setInterval(callback_fn, time_in_ms)

“setInterval()” takes 2 parameters, first is a callback function that triggers after the delay, and the second is the delay provided in milliseconds.

Example

In this example, we will use the “setInterval()” browser API to refresh our web application after every 2 seconds.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>How to Automatic Refresh a web page in fixed time?</title>
</head>
<body>
   <h3>How to Automatic Refresh a web page in fixed time?</h3>
   <script>
      window.onload = () => {
         console.clear()
         console.log('page loaded!');
         setInterval(() => {
            window.location = window.location.href;
         }, 2000)
      }
   </script>
</body>
</html>

Conclusion

In this article, we learned how to automatically refresh our web application after a fixed amount of time using both, HTML5 and javascript using two different approaches. In the first approach, we used the “http-equiv” property of the “meta” tag, and in the second approach, we used the “setInterval” browser API.

Updated on: 22-Feb-2023

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements