Memory leak in jQuery AJAX calls

I wrote a small chat widget that launches an ajax call every second to receive new messages that have been posted. The problem is that this is a memory leak, and only 15 minutes after opening it, it disables my browser (Firefox).

I probably, since I'm a relative newbie, and I'm sure something has missed or not disconnecting 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 take a look at my (main) code and see if you can find out where the memory leak is and what am I doing wrong? Do I need to disable some variables or something like that?

Many thanks!

+5
source share
1 answer

setInterval() ajax, . setTimeout(), , , setTimeout() complete.

.

$(DoMyAjax); // start your ajax on DOM ready
function DoMyAjax() {
   $.ajax({ 
      complete: function() {
          // your logic here
          setTimeout(DoMyAjax, 1000);
      }
   });
}
+5

All Articles