开发者

How to stop a current ajax connection and start a new one?

i have a chat box that will load new messages using ajax on my content page and it will listen for new ones every 20s. It is working. However, right now i have another link that will allow a user to load previous messages. And that button does not seem to work even though i have already done a clearTimeout() on the exist开发者_如何学Going ajax function. any idea why?

My scripts:

   //for loading previous messages

    var timer;       

    $('#getoldmessages').click(function() {

        $("#workroom_boxes_chatpast").html('<img src="{{ MEDIA_URL }}images/ui-anim_basic_16x16.gif"/>&nbsp; Loading...');
        $.ajax({
            url: "/messages/{{ chat.key.id }}",
            cache: false,
            success: function(html){
                $("#chatcontent").html(html);
                $("#workroom_boxes_chatpast").html('Loaded');
            }
        });
                    clearTimeout(timer);

});      



   //for new messages

function updateMsg() {
$.ajax({
url: "/recent/messages/{{ chat.key.id }}",
cache: false,
success: function(html){
$("#chatcontent").html(html);
}
});
//alert('repeating');
t = setTimeout(updateMsg, 20000);
}
updateMsg();


setTimeout(this, 20000); is broken, this refers to a jquery object in that context, not a function. Check your javascript console and you'll see an error.

You don't need to clearTimeout to make a separate ajax call. Moreover, your call might not work because you're referring to the variable timer which has the timeout id from the first call to setTimeout, but any successive call will return a new id. So you need to add in your updateMsg the variable assignment: timer = setTimeout(updateMsg,20000);.

If your initial code is being executed in a $() block separate from updateMsg, then timer will only be visible in that block and changing that in updateMsg won't have an effect, another problem. If so, either make timer global, or attach it to a global object, or put updateMsg in that $() block.

Lastly, you should be using setInterval anyway, instead of recalling setTimeout every time, that's what it is made for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜