日期:2014-05-16  浏览次数:20485 次

关于setTimeout内存溢出的问题.
我的代码是大概是这样:
var settimeout_id=null; //定時器刪除.
var urls="system/ajax_book.php";
function a()
{
  $.ajax({
  type:"get",
  url:urls,//全局变量,请求的页面返回数据是:2-3KB
  ifModified:true, //false也試過不行
  cache: true, //false也試過.
  dataType:"json",
  error:function(){alert("Please refresh the page or restart the browser")},
  success:function(table_date){b(table_date);}
  });
}

function b(str)
{
  $("#page_scroll").empty(); //清空原來获取的数据.page_scroll是一个<ul>
  if(str!=null && str.length>0)
  { 
  var table_str="";
   
  //獲取了數據
  table_str+="<li id='数据'>数据</li>";
  $("#page_scroll").html(table_str); //添加到ul中
 
//这段代码就产生了IE内存溢出,如果我去除这段代码则没有.
if(settimeout_id!=null || settimeout_id!="")
{
table_str=null;
window.clearTimeout(settimeout_id); //清除settimeout函數產生的內存消耗.
settimeout_id=null;
// 每隔 5 秒释放一次内存
if(isIE){ CollectGarbage();}
}
//就是不加上面的代码溢出的更厉害.
settimeout_id=window.setTimeout("a()",5000); //設置自動刷新.

  }
}
最后
$(document).ready(function(){
  a();
})

//我应该怎么样修改这个局部定时刷新,才不会内存溢出呢?
另外我用的内存溢出测试工具是:
http://download.csdn.net/source/1814153

------解决方案--------------------
探讨

我的贴发在JavaScript版面没有响应...
我的要当settimeout_id不等于null 或者不为空的情况..就是表示之前有一个setTimeout了.
才做清除.

------解决方案--------------------
dingsontao说得没错,应该是&&关系,不是||关系
JScript code
function b(str) {
    $("#page_scroll").empty(); // 清空原來获取的数据.page_scroll是一个<ul>
    if (str != null && str.length > 0) {
        var table_str = "";

        // 獲取了數據
        table_str += "<li id='数据'>数据</li>";
        $("#page_scroll").html(table_str); // 添加到ul中

        // 应该是并且的关系
        if (settimeout_id != null && settimeout_id != "") {
            table_str = null;
            window.clearTimeout(settimeout_id); // 清除settimeout函數產生的內存消耗.
            settimeout_id = null;
            // 每隔 5 秒释放一次内存
            if (isIE) {
                CollectGarbage();
            }
        }
        settimeout_id = window.setTimeout("a()", 5000); // 設置自動刷新.
    }
}

------解决方案--------------------
这个可能是更你请求的页面的数据量有关系...
可能你请求的数据量大,而且又是隔5秒刷新一次...
试试延长一点时间...
将$("#page_scroll").empty();
改成$("#page_scroll").html("");