How to automatically refresh a web page in a fixed time using CSS

How to Automatically Refresh a Web Page in CSS

We can automatically refresh a web page by using the “meta” tag with the “http-equiv” attribute, or by using the setInterval() browser API. Automatically refreshing a website can be useful. For example, if we were creating a weather web application, we might want to refresh our website after a set time interval to show users nearly accurate weather data for a specific location.

Let’s look at the following two methods to learn how to set up an automatically refreshing website.

Method 1

In this method, we’ll use the “http-equiv” attribute of the “meta” tag to refresh our web app after a specific time interval, which is passed in its “content” attribute. This meta tag is provided to us by default in the HTML5 specification.


Grammar

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

Here, “n” is a positive integer representing the number of seconds after which the page should be refreshed.

Example

In this example, we’ll use the “http-equiv” attribute of the “meta” tag to refresh our web application every 2 seconds.

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

Method 2

In this method, we will use the “setInterval()” API provided by the browser, which allows us to run a piece of code after a certain amount of time. Both parameters are passed as parameters to the browser API.

Syntax

setInterval(callback_fn, time_in_ms) 

“setInterval()” requires two parameters: the first is the callback function to be triggered after the delay, and the second is the delay in milliseconds.

Example

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

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

Summary

In this article, we learned how to automatically refresh our web application after a fixed time using two different methods using HTML5 and JavaScript. In the first method, we used the “http-equiv” attribute of the “meta” tag; in the second method, we used the “setInterval” browser API.

Leave a Reply

Your email address will not be published. Required fields are marked *