How to Fire AJAX Request on Regular Interval

There are many cases where we have required to update certain part of the web page on the regular basis.

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

In this tutorial, I show How to use jQuery AJAX to implementing this.

There are two ways to send AJAX request on 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 on 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 it 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 has sent the new one.

I show How you can solve this problem using setTimeout().

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.

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);
});

In some way, we have created a recursion here. Setting time for next execution of the function when the previous request is complete.

3. Conclusion

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

You can use setInterval() when you want to send AJAX request at particular interval every time and doesn’t want to rely on the previous request is completed or not.

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


Originally published at makitweb.com .