douhuan5073 2018-09-11 07:52
浏览 54

如何停止函数重载

$('.contact').click(function() {
$('.cont').not(this).removeClass('active');
$(this).addClass('active');

var limit = 8;
var start = 0;

sendRequest(limit, start);
loader();

function loader (){
    var scrollTop = $('.messages').scrollTop();
    if (scrollTop <= 0) {
        $('.signal2').show();
    } else {
        $('.signal2').hide();
    }  
    setTimeout(function() { loader(); }, 500);
};

function sendRequest(limit, start) {
    var scrollPosition = $('.messages').scrollTop();
    var scrollHeight = $('.messages')[0].scrollHeight;
    var convo_id=document.getElementById("convo_id").value;

    $.ajax({
        cache: false,
        type: "POST",
        url: 'show_chat.php',
        data: ({ convo_id: convo_id, limit: limit, start:start }),
        success: function(data) {
            alert(limit);
            if (data != '') {
                var scrollTop = $('.messages').scrollTop();
                if (scrollTop <= 0)  { 
                    limit = limit + 8;
                    $('.messages').scrollTop(30);
                }
            }
            if (scrollPosition + $('.messages').height() === scrollHeight) { 
                $('.messages').animate( { scrollTop:scrollHeight},700);       
            }
        },
        complete: function() {
            // Schedule the next request when the current one's complete
            setTimeout(function(){ sendRequest(limit, start); }, 2000); // The interval set to 5 seconds
        }
    });
 }; 

This is my code, I'll try my best to explain:

  • $('.contact').click(function() { is when the user selects a contact person.
  • limit is the limit to the query that fetches the user chats.
  • convo_id is used to find the user conversation.

Now, everything works fine but, when i'm on a particular chat conversation, and i loaded more chats by scrolling the page to the top for 3 times, my current limit value would be 8*3=24.

Therefore you can see i call this function function sendRequest(limit, start){ from the timeout call passing the parameter (limit=24) with an interval of 2 secs (keeping the chat page up to date).

But, the problem arises when i select a different contact person. The convo_id changes and the $('.contact').click(function() { calls sendRequest() with the parameter (limit=8).

However, the same function is called by the timeout with the old parameter at the same time (limit=24). Therefore, the whole page flickers between displaying two sets of results to and fro (8 messages and 24 messages) every sec.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 ETLCloud 处理json多层级问题
    • ¥15 matlab中使用gurobi时报错
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭
    • ¥15 2020长安杯与连接网探
    • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
    • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
    • ¥15 可见光定位matlab仿真
    • ¥15 arduino 四自由度机械臂
    • ¥15 wordpress 产品图片 GIF 没法显示