Auto refresh page every 30 seconds

JavascriptHtml

Javascript Problem Overview


I have a JSP page which has to display the status of various jobs that are running. Some of these jobs take time, so it takes a while for their status to change from processing to complete.

Is it a good idea to have a javascript function that would refresh the page every 30 seconds or so? Are there any ramifications for having a script that is constantly refreshing a page?

The other option is to have a refresh button which on click would refresh the page.

Javascript Solutions


Solution 1 - Javascript

There are multiple solutions for this. If you want the page to be refreshed you actually don't need JavaScript, the browser can do it for you if you add this meta tag in your head tag.

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

The browser will then refresh the page every 30 seconds.

If you really want to do it with JavaScript, then you can refresh the page every 30 seconds with Location.reload() (docs) inside a setTimeout():

window.setTimeout( function() {
  window.location.reload();
}, 30000);

If you don't need to refresh the whole page but only a part of it, I guess an AJAX call would be the most efficient way.

Solution 2 - Javascript

Just a simple line of code in the head section can refresh the page

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

although its not a javascript function, its the simplest way to accomplish the above task hopefully.

Solution 3 - Javascript

If you want refresh the page you could use like this, but refreshing the page is usually not the best method, it better to try just update the content that you need to be updated.

javascript:

<script language="javascript">
setTimeout(function(){
   window.location.reload(1);
}, 30000);
</script>

Solution 4 - Javascript

Use setInterval instead of setTimeout. Though in this case either will be fine but setTimeout inherently triggers only once setInterval continues indefinitely.

<script language="javascript">
setInterval(function(){
   window.location.reload(1);
}, 30000);
</script>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaryView Question on Stackoverflow
Solution 1 - JavascriptjeerblView Answer on Stackoverflow
Solution 2 - Javascript404View Answer on Stackoverflow
Solution 3 - JavascriptPatrik FröhlerView Answer on Stackoverflow
Solution 4 - Javascriptishandutta2007View Answer on Stackoverflow