jQuery AJAX调用中的内存泄漏 [英] Memory leak in jQuery AJAX calls

查看:129
本文介绍了jQuery AJAX调用中的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个聊天框小部件,它每秒运行一次ajax调用,以获取已发布的新消息.问题在于它正在泄漏内存,仅在打开大约15分钟后便崩溃了我的浏览器(Firefox).

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?

非常感谢!

推荐答案

切勿setInterval()与ajax一起使用,否则您的请求将永远不会保持同步.改用setTimeout(),然后等待逻辑处理,在complete回调中递归启动setTimeout().

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.

示例.

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

这篇关于jQuery AJAX调用中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆