Refresh content automatically after some period time – jQuery

If you just need to refresh your page or content every x seconds you just need some javascript. I show you some basics with jQuery. 

Most important method

setInterval(function,milisec,lang);

It’s javascript primary method which allow us to call some function every x miliseconds. You can read more about it at w3schools.com

I’ll be using it in all my examples. First two parameters are required, while third is optional. Remember that 1s = 1000ms.

For example if I want to call function my_function() every 5 seconds (5 seconds * 1000 = 5000ms) I just write it like this:

setInterval("my_function();",5000); 

Refresh whole page

Sometimes we need to refresh whole page. It’s not so common now because it’s timeconsuming and bad for performance, but it needs to be mention. So to refresh page every 5 seconds our code would look like that:

<script type="text/javascript">
  setInterval("my_function();",10000); 
 
    function my_function(){
        window.location = location.href;
    }
</script>

Refresh part of the page

If you need to refresh content in some div of the page you can use jQuery load() function. 

$('#id_for_refresh').load('your_url #id_of_loaded_content');

For better understanding see example below:

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js">
  <script type="text/javascript">
    setInterval("my_function();",5000); 
    function my_function(){
      $('#refresh').load(location.href + ' #time');
    }
  </script>
</head>
<body>
  <div id="refresh"></div>
  <div id="time">
    <?php echo date('H:i:s');?>
  </div>  
</body>
</html>

You can see that every 5 sec div with id=”refresh” is updated. Of course our div in html can look like this 

<div id="refresh">
  <div id="time">
    <?php echo date('H:i:s');?>
  </div>
</div>

i used two separate containers so you can see the changes. You can also specify the url for other page, or send some data to it. But this is used more with interaction with user and not with auto refreshing.

If you also want to see something more complicated, check Volume II of ajax auto refresh with working example.

3.4 12 votes
Article Rating