I've written a little chat-box widget which runs an ajax call every second, to fetch new messages that have been posted. The problem is it's leaking memory, and after only about 15 mins of being open it crashes my browser (Firefox).
It's probably me, as I am a relative newbie, and I'm sure I've missed something out or am not unsetting my variables, etc..
var chat = {}
chat.fetchMessages = function() {
$.ajax({
url: '/chat_ajax.php',
type: 'post',
data: { method: 'fetch'},
success : function(data) {
$('#chat .messages').html(data);
$("#chat").scrollTop($("#chat")[0].scrollHeight);
}
});
}
chat.interval = setInterval(chat.fetchMessages, 1000);
chat.fetchMessages();
Can someone please glance at my (basic) code, and see if you can spot where the memory leak is occuring, and what I'm doing wrong? Do I need to unset some variables or something?
Many thanks!
Never use setInterval()
with ajax, otherwise your requests never stay synchronized. Use setTimeout()
instead and then pending your logic, initiate the setTimeout()
recursively in the complete
callback.
Example.
$(DoMyAjax); // start your ajax on DOM ready
function DoMyAjax() {
$.ajax({
complete: function() {
// your logic here
setTimeout(DoMyAjax, 1000);
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With