我想建立一个d3布局,不断收集新数据并相应地更新可视化。这是我的想法(随机生成的数据)的工作原型:
<!DOCTYPE html>
<html>
<body>
<script src="d3/d3.min.js" charset="utf-8"></script>
<script type="application/javascript">
var width = window.innerWidth;
var height = window.innerHeight;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var layout;
iterateLayout(svg, 0);
function iterateLayout(svg, counter) {
if(counter % 3 == 0)
layout = generateLayout(20);
else if(counter % 3 == 1)
layout = generateLayout(100);
else
layout = generateLayout(500);
layout.force.start();
console.log("Force computations begin");
layout.force.on("end", function() {
console.log("Force computations complete");
displayLayout(svg, layout);
console.log("Layout should be visible, starting next layout computation");
iterateLayout(svg, counter + 1);
});
}
function generateLayout(numNodes) {
var nodes = [];
var links = [];
for(var i = 0; i < numNodes; i++)
nodes.push({"name": i});
var index;
for(var i = 0; i < numNodes; i++)
for(var j = 0; j < 4; j++) {
index = Math.floor((Math.random() * numNodes));
if(i != index)
links.push({"source": i, "target": index});
}
var force = d3.layout.force()
.size([width, height])
.nodes(nodes)
.links(links);
return {"force": force, "nodes": nodes, "links": links};
}
function displayLayout(svg, layout) {
svg.selectAll("*").remove();
var links = svg.selectAll(".link")
.data(layout.links)
.enter()
.append("line")
.attr("class", "link")
.style("stroke", "black");
var nodes = svg.selectAll(".node")
.data(layout.nodes)
.enter()
.append("circle")
.attr("class", "node")
.attr("r", 4)
.style("fill", "black");
links
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
nodes
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
</script>
此代码的行为与我想要的完全相同,除了它依赖于iterateLayout
函数的无限递归调用。除了这是一个内存泄漏这一事实,这意味着代码最终将消耗浏览器的调用堆栈并抛出错误。
所以我想用无限循环替换无限递归。简单地将相关代码括在while(true)
块中的问题是循环不会等待&#34;结束&#34; d3.layout.force()
中的事件在继续循环的下一次迭代之前触发。因此我的问题是: