我有两个按钮,这两个按钮应该显示两个不同的图形系列。每一系列图形逐渐显示,一个接一个,延迟3秒。如果用户单击第一个按钮,他将逐渐显示第一个系列,如果用户单击第二个按钮,第一个系列将被删除,第二个系列开始逐个逐渐显示。
下面是这段代码:
<button type="button" onclick="show_graphs(1)"></button>
<button type="button" onclick="show_graphs(2)"></button>
<div id="stats"></div>
function show_graphs(type) {
var i = 0;
$('#stats').html('');
$.getJSON('stats.php?type=' + type, function (data) {
for (chartData in data) {
i++;
var timer = setTimeout(function(index,d1){
return function() {
var chart = new AmStockChart();
dataSet.dataProvider = data[d1];
// etc. etc.
$('#stats').append('div id="chartdiv' + index + '"></div>');
chart.write("chartdiv" + index);
}
}(i,chartData), 3000*i);
}
});问题是,如果用户在第一个系列完成附加之前单击第二个按钮,那么div将被清除,但是第一个系列继续附加它的图形,然后第二个系列被附加。因此,根据我的理解,在使用另一个参数再次运行setTimeOut之前,我需要先停止它。我知道我需要用
clearTimeout(timer)..。但是我不知道该在哪里使用它。无论我把它放在哪里,我都会得到‘未知变量定时器’。
发布于 2013-10-27 21:05:36
请注意,必须在超时持续时间之前调用clearTimeout()才能生效,即在调用绑定函数之前。其次,在您的例子中,由于图形渲染已经开始,仅有clearTimeout()是不够的。
您可以使用某种标志来指示是否应该中止图形呈现操作。
对于ex:
// cancel indicator
var cancelGraph = {}, timer;
function show_graphs(type) {
// abort any other rendering
clearTimeout(timer); // clear timeout if rendering not already started
// cancel other running operations
for(var otherType in cancelGraph) {
if(otherType !== type) cancelGraph[otherType] = true;
}
$('#stats').html('');
// set current one as non-cancelled
cancelGraph[type] = false;
var i = 0;
$.getJSON('stats.php?type=' + type, function (data) {
for (chartData in data) {
if(cancelGraph[type] === true) break; // abort: don't continue rendering
i++;
timer = setTimeout(function(index,d1){
...
}(i,chartData), 3000*i);
}
});
}https://stackoverflow.com/questions/19618279
复制相似问题