Open In App

How to Automatic Refresh a Web Page in a Fixed Time?

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

To automatically refresh a web page in a fixed time, we will predefine a time, and the browser will automatically refresh the webpage after that specified time.

There are two methods to automatically refresh a web page in a fixed time:

Let’s understand these two approaches in detail below. We will cover these methods with syntax and examples, to get a better understanding.

1. Using a “meta” tag to Automatically Refresh a Web Page

To automatically refresh a web page in fixed time intervals, use the meta tag with the http-equiv attribute set to “refresh” and the content attribute specifying the time in seconds.

Syntax:

<meta http-equiv="refresh" content="(time in seconds)">

Example: This example shows the above-explained approach.

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
    <meta http-equiv="refresh" content="10">
</head>

<body>
    <h2>Welcome To GFG</h2>
    <p>The code will reload after 10s.</p>
</body>
</html>

Output:

automatically reload web page using meta tag

2. Using the setInterval() method to Automatically Refresh a Web Page

An alternative method to implement automatic page refresh is by using JavaScript’s setInterval() function. Until clearInterval() is called to stop it, setInterval() will continuously invoke the specified function at regular intervals, effectively providing an auto-refresh behavior on the webpage.

Syntax:

<script>
function autoRefresh() {
window.location = window.location.href;
}
setInterval('autoRefresh()', 5000);
</script>

Example: In this example, we have used setInterval() to reload the page every 2 seconds (2000 milliseconds).

HTML
<!DOCTYPE html>
<html>
<head>
    <title>
        Reloading page after 2 seconds
    </title>

    <script>
        function autoRefresh() {
            window.location = window.location.href;
        }
        setInterval('autoRefresh()', 2000);
    </script>
</head>

<body>
    <h1>Welcome to GeeksforGeeks code</h1>
</body>
</html>

Output:

automatically reload web page using setinterval methd


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads