How to use the setInterval() method to Automatically Refresh a Web Page In Javascript

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 w3wiki code</h1>
</body>
</html>

Output:


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

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:

Table of Content

  • Using a “meta” tag to Automatically Refresh a Web Page
  • Using the setInterval() method to Automatically Refresh a Web Page

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

Similar Reads

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....

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....