How to Auto Refresh Page Every 10 Seconds using JavaScript setInterval() Method

← PrevNext →

The JavaScript setInterval() method calls a function or executes a code repeatedly at specified time intervals. Here in this post, I’ll show you a simple example on how to refresh or reload a web page every 10 Seconds using the JavaScript setInterval() method.

Syntax of setInterval() Method

window.setInterval(code, delay)

Related Post: Create a Simple Digital Clock in JavaScript using setInterval() Method

The method setInterval() takes two parameters. The code to execute and a delay in milliseconds (to execute the code) . The code can also be a function. In the example below, I am calling a function (a user defined function).

The Script
<script>
    window.setInterval('refresh()', 10000); 	// Call a function every 10000 milliseconds (OR 10 seconds).

    // Refresh or reload page.
    function refresh() {
        window .location.reload();
    }
</script>

Note: You can ignore the window prefix with the method.

Create a Countdown using setInterval() Method

You can create a countdown using the setInterval() method, which will show the seconds left before the page will automatically load. The method will update a <span> element every second. Use this countdown example to notify users for upcoming events or a deal that is going end very soon, etc.

The Markup
<div>This page will reload in <span id="cnt" style="color:red;">10</span> Seconds</div>
The Script
<script>
    var counter = 10;

    // The countdown method.
    window.setInterval(function () {
        counter--;
        if (counter >= 0) {
            var span;
            span = document.getElementById("cnt");
            span.innerHTML = counter;
        }
        if (counter === 0) {
            clearInterval(counter);
        }

    }, 1000);

    window.setInterval('refresh()', 10000);

    // Refresh or reload page.
    function refresh() {
        window  .location.reload();
    }
</script>

Also Read: Refresh DIV element with XML Data Automatically without Reloading the Entire Page

Conclusion

The JavaScript setInterval() method can be used for a variety of purpose, using various execution methods, such as a button click. I have just showed two simple examples on how to use the method to execute a function automatically and repeatedly.

Tip: You can Auto Refresh a page using the <meta> tag. This in case you do not want to use JavaScript or jQuery for this purpose. Add the below tag inside the <head> tag.

<meta https-equiv="refresh" content="10">

The content attribute has a value in seconds. The period it will wait before refreshing the page automatically.

However, the JavaScript method that I have explained has many other benefits. For example, you can explicitly invoke the auto refresh procedure, when every necessary.

That’s it. Happy Coding. 🙂

← PreviousNext →