如何仅在需要时处理ajax请求,而不是每秒都处理

Basically, I am developing an ajax chat (php, mysql, javascript, ajax) there is part of the code where I fetch all chat messages inside a div by using ajax, the ajax function is running every 2 sec.

My main problem is that the div is scrolling down every 2 sec, I need it to scroll down only when there is new entry (scroll down for all chat users not me only)

function loadLog(){     
    var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
    $.ajax({
        url: "ajaxchat.php",
        cache: false,
        success: function(html){
            $("#chatbox").html(html); //Insert chat log into the #chatbox div               
            var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
            if(newscrollHeight > oldscrollHeight){
                $("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //i need to scroll if only there is new entry not every 2.5 sec 
            }               
        },
    });
}
setInterval (loadLog, 2500);    //Reload file every 2.5 seconds

You can't do this with LAMP You need response to events from server. You can do this with this stack


Your server need response to database events. PHP response to Client events.

A simple solution would be to check the new HTML is different to the old HTML before updating the chatbox. This will ensure that the chatbox is only updated when new content is fetched from the server. However if you response HTML is inconsistent this will not work.

var previousChatHTML = '';
function showChatMessages(html) {
    if(previousChatHTML === html){
        return;
    }
    var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
    $("#chatbox").html(html); //Insert chat log into the #chatbox div  
    previousChatHTML = html;   
    var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
    if(newscrollHeight > oldscrollHeight){
        $("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //i need to scroll if only there is new entry not every 2.5 sec 
    }               
}

function loadLog(){     
    $.ajax({
        url: "ajaxchat.php",
        cache: false,
        success: showChatMessages,
    });
}
setInterval (loadLog, 2500);    //Reload file every 2.5 seconds

Also when creating pollers in JS you may want to use setTimeout (https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) instead of setInterval as on slow connections you can get odd results (if a request takes longer than 2.5s it can resolve in the wrong order).