我试图在示例here中找到内存泄漏:
document.addEventListener('DOMContentLoaded', bindTabs);
function bindTabs(){
var lastTab,
tabs = document.querySelectorAll(".tabs li"),
i;
function selectTab(){
activateTab(this);
loadContent(this.attributes["data-load"].value);
}
function activateTab(tab){
if (lastTab) {
lastTab.classList.remove("active");
}
(lastTab = tab).classList.add("active");
}
[].forEach.call(tabs, function(el){
el.addEventListener('click', selectTab, false);
});
}
function loadContent(url){
getContent(url).then(function(data){
prepareContent(data);
prepareGallery();
})
}
var lastDiv;
function prepareContent(data){
var content = document.getElementById("content"),
div = document.createElement("div");
div.innerHTML = data;
if (lastDiv) {
content.removeChild(lastDiv);
}
content.appendChild(div);
lastDiv = div;
}
function prepareGallery(){
var width = 426,
forward = false,
position = 0,
elements = document.querySelectorAll(".gallery li"),
number = elements.length;
function checkDirection() {
if (position === 0) {
forward = true;
} else if (position === (number - 1)) {
forward = false;
}
}
function changeLeftProperty() {
var value = (-1 * width * position) + "px";
[].forEach.call(elements, function(el) {
el.style.left = value;
});
}
function advance(){
position = position + (forward ? 1 : -1);
}
function move(){
checkDirection();
advance();
changeLeftProperty();
}
setInterval(move, 2000);
}
function getContent(url){
var callbacks = [],
xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function(e){
if (xhr.status == 200) {
callbacks.forEach(function(cb){
cb(xhr.response);
})
}
}
xhr.send()
return {
then: function(fn){
callbacks.push(fn)
}
}
}
我通过获取堆快照并运行时间轴来分析页面,但遗憾的是我无法找到任何内容。
你能否告诉我问题出在哪里?确切的内存泄漏(如果有的话)是什么?
答案 0 :(得分:2)
setInterval(move, 2000);
中的prepareGallery
每次点击都会被调用,而且没有clearInterval
。