Zak
Zak

Reputation: 7525

Simple AJAX seems to quietly overwhelm browser

I have a small AJAX, within a recursive function, and a setTimeout on complete. Since I have implemented this, I have clients complaining about lag after a few hours of sitting on the page...

get_activity();

function get_activity() {
    var activity = $.ajax({
        type: "POST",
        url: "/ajax/activity.php",
        async: false
    }).complete(function () {
        setTimeout(function () {
            get_activity();
        }, 5000);
    }).responseText;

    $('#activity').html(activity);
}

Being that it's in a callback, .complete and that it's on a setTimeout of 5 seconds, I thought it would be safe to run. The response is nothing more than a table with exactly 1,000 rows (based on LIMIT in mysql call) and 3 columns. Nothing huge:

<table style="font-size:9px; width:100%; font-weight:bold; color:#FFF;">
<?php foreach ($activity_log as $item): ?>
    <tr>
        <td style="width:60px;">
            <?= $item['user'] ?>
        </td>
        <td style="width:120px;">
            <?= $item['activity'] ?>
        </td>
        <td style="width:100px;">
            <?= date('M j, Y G:i', strtotime($item['date_completed'])); ?>
       </td>
    </tr>
<?php endforeach; ?>
</table>

If you notice in my AJAX I am using

$('#activity').html(activity);

vs

$('#activity').append(activity);

So $('#activity')s DOM element is being overwritten every time. So I know I am not loading the browser up that way.

I feel that I am doing everything right -- Not loading up the requests, effectively making them synchronous -- And I am not loading up the DOM, rather I am clearing and filling the div with each request.

Does anyone see a reason this script and it's response would cause both Chrome and FF to load up and lag after a few hours on the page?

Upvotes: 1

Views: 49

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075059

Beware constantly polling like that. It's generally poor practice. This article offers some alternatives.

But to your ajax call:

When you use async: false, you make the ajax call synchronous, which means that while the network operation is happening, no other JavaScript can run and in most browsers, the page is completely nonresponsive.

Remove the async: false and instead use the success callback:

function get_activity() {
    $.ajax({
        type: "POST",
        url: "/ajax/activity.php",
        // *** Use the `success` callback
        success: function(text) {
            $('#activity').html(text);
        },
        complete: function() {
            setTimeout(function () {
                get_activity();
            }, 5000);
        }
    });
}

Upvotes: 3

Related Questions