How to Send AJAX Request at Regular Interval

On 3/15/2018

At times, you may want to update part of a web page repeatedly. Let's say, for example, that you have a website flashing live news or a cricket score update. Here you have to refresh that specific content on a regular basis and ajax is the best way to do it.

You are left with two options when you want to fire ajax request at specific time interval - one is setInterval() and the other is setTimeout() function. Both JavaScript functions are good for doing periodic tasks, but one is much better than the other. In this tutorial we will see what is the best approach and how.

send ajax request at regular interval

Fire Continuous AJAX Request using setInterval():

The setInterval() is the common method used for repeated tasks. It executes a function at specified interval in milliseconds. Repeated calls can only be stopped using the clearInterval() method or by closing the window.

setInterval(function, milliseconds);

Consider the following example. This java script will fire ajax call every 5 seconds to the server and update the news feed.

<script type="text/javascript">
function getFeed() {
    $.ajax({
        url: 'get_news_feed.php',
        type: 'POST',
        success: function(data) {
            $('#result').html(data);
        }
    });
}

$(document).ready(function() {
    setInterval(getFeed, 5000);
});
</script>

At first glance, the script may look fine but it's not. It continuously executes the getFeed() function regardless of whether the previous ajax request is completed or not.

Let's say you are on a slower network, and the first request was not completed, but you start another one. Soon you would end up in a situation where multiple requests are stacked up that consume shared resources and delay each other.

To avoid this problem, you can use the setTimeout() method that allows you to wait until the last request is completed before sending the next one.

Using setTimeout() Method:

The setTimeout() calls a function after the specified delay. Unlike the previous method, it executes the function only once. You have to call again to repeat the execution.

setTimeout(function, milliseconds);
It's best to use setTimeout() method instead of setInterval() for tasks that take longer than the repetition time interval.

Below is an example for its usage.

<script type="text/javascript">
function getFeed() {
    $.ajax({
        url: 'get_news_feed.php',
        type: 'POST',
        success: function(data) {
            $('#result').html(data);
        },
        complete:function(data) {
            setTimeout(getFeed, 5000);
        }
    });
}

$(document).ready(function() {
    setTimeout(getFeed, 5000);
});
</script>

The above script send ajax request after waiting for 5 seconds. Upon successful completion, the next one will be fired. Here we have used the complete callback to verify if the previous request was executed successfully or not.

As you can see, the second example is much better than the first. It simply waits for the first ajax call to finish before sending the second one. So even if there is a delay for server response, multiple requests won't be queued.

Also Read:

We have seen two ways to send an ajax call at specific time interval. And the post also explains why it is better to use setTimeout for repetitive task. I hope this post is useful for you. Please share it on social media if you like it.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *