Memory leak in jQuery AJAX calls

不问归期 提交于 2019-12-19 08:33:51

问题


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!


回答1:


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);
      }
   });
}


来源:https://stackoverflow.com/questions/15414094/memory-leak-in-jquery-ajax-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!