Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak in jQuery AJAX calls

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!

like image 868
Neil Hillman Avatar asked Mar 14 '13 15:03

Neil Hillman


1 Answers

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);
      }
   });
}
like image 178
Brad M Avatar answered Oct 04 '22 02:10

Brad M