JavaScript

Auto Refresh Page Every 30 Seconds – JavaScript

Most of the time, in many web applications, developers need to refresh the page automatically after a particular time. For instance, in stock exchange applications or sports scores, where the data is changed and updated frequently to display. Automatically refreshing the page can provide users with the latest information without requiring them to refresh the page manually.

This post will describe the method to refresh the page after every 30 seconds in JavaScript.

How to Auto Refresh Page Every 30 Seconds Using JavaScript?

To auto refresh the page after every 30 seconds, use the following methods:

Method 1: Auto Refresh Page Every 30 Seconds Using “setInterval()” Method

Use the “setInterval()” method for auto refreshing the page. It is a built-in JavaScript method that allows to execute a function repeatedly at a specified interval.

Syntax
Follow the given syntax for the setInterval() method:

setInterval(function, milliseconds);

It takes two parameters, the “function” to be executed and the “time interval” (in milliseconds) at which to execute the function.

Example
Call the “setInterval()” method by passing a function and time interval, which is 30 seconds in milliseconds “30000”. In the function, call the “window.location.reload()” method to reload the page:

setInterval(function(){
 window.location.reload(1);
 alert("Refreshed");
}, 30000);

The output shows an alert message while refreshing the page after 30 seconds:

Method 2: Auto Refresh Page Every 30 Seconds Using “setTimeout()” Method

Another way to refresh the page automatically is to use the “setTimeout()” method. It allows the execution of a function after a specified delay/time.

Syntax
Use the following syntax for the setTimeout() method:

setTimeout(function, milliseconds);

Similar to setInterval, it also takes the two parameters “function” and “time interval”.

Example
Call the setTimeout() by passing delay time and a function for reloading page using the “location.reload(true)”:

setTimeout("location.reload(true);", 30000);
alert("Refreshed");

Output

That’s all about refreshing the page automatically after every 30 seconds.

Conclusion

For refreshing the page automatically after 30 seconds, use the “setInterval()” method or the “setTimeout()” method. Both methods execute the specified function within a particular time period. This post described the method to refresh the page after every 30 seconds in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.