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 existing 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"/> 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,thisrefers 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
clearTimeoutto make a separate ajax call. Moreover, your call might not work because you’re referring to the variabletimerwhich has the timeout id from the first call tosetTimeout, but any successive call will return a new id. So you need to add in yourupdateMsgthe variable assignment:timer = setTimeout(updateMsg,20000);.If your initial code is being executed in a
$()block separate fromupdateMsg, then timer will only be visible in that block and changing that inupdateMsgwon’t have an effect, another problem. If so, either maketimerglobal, or attach it to a global object, or putupdateMsgin that$()block.Lastly, you should be using
setIntervalanyway, instead of recallingsetTimeoutevery time, that’s what it is made for.