Javascript

How to fire AJAX Request on Regular Interval?

People are searching for a better answer to this question.
1 answer

There are many cases when require to update certain parts of the web page on a regular basis.

For example – showing live cricket or football score, display the latest news feeds, etc.

There are two ways to send AJAX request at a specified time 

  • By setInterval() and
  • By setTimeout() JavaScript functions.

Both do the same work but they are reliable for certain cases, which I discuss in this tutorial.

1. Using setInterval()

setInteval()

It repeatedly calls the function on the given interval for stop you need to clear the interval using clearInterval() or close the window.

Syntax –

setInterval(function, milliseconds);

Example

Creating a function which calls the AJAX request and using this function in setInterval() and set Interval for 5 sec.

Now the function executes every 5 seconds and fetches new data from the server.

function fetchdata(){
 $.ajax({
 url: 'fetch_details.php',
 type: 'post',
 success: function(response){
 // Perform operation on the return value
 alert(response);
 }
 });
}

$(document).ready(function(){
 setInterval(fetchdata,5000);
});

The above code works and does its job, but it has one problem –

It repeatedly executes the function even when the previous AJAX request is not successfully executed and return.

For example – If the user has on the slow network and you are sending the request on every 5 seconds but what if the previous request doesn’t complete and you have sent the new one.

To avoid these types of problems use setTimeout() function.

2. Using setTimeout()

setTimeout()

It calls the function once after the given interval. To continue the execution you need to call it again.

Syntax –

setTimeout(function,milliseconds)

Example

Using complete in AJAX to check whether the previous request successfully executed or not. If successfully executed then again define setTimeout() method.

function fetchdata(){
 $.ajax({
 url: 'fetch_details.php',
 type: 'post',
 success: function(data){
 // Perform operation on return value
 alert(data);
 },
 complete:function(data){
 setTimeout(fetchdata,5000);
 }
 });
}

$(document).ready(function(){
 setTimeout(fetchdata,5000);
});

3. Conclusion

I showed you how you can use setInterval() and setTimeout() function to send AJAX requests constantly.

Use setInterval() when you want to send AJAX request at a particular interval every time and don’t want to depend on the previous request is completed or not.

But if you want to execute the AJAX when the previous one is completed then use the setTimeout() function.