0

我有两个按钮,它们应该显示两个不同系列的图形。每个系列的图表以 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 将被清除,但第一个系列继续附加其 graps,然后第二个系列被附加。因此,据我所知,我需要先停止 setTimeOut,然后再使用另一个参数第二次运行它。我知道我需要使用

clearTimeout(timer)

...但我不知道在哪里使用它。无论我把它放在哪里,我都会得到“未知变量计时器”。

4

1 回答 1

2

请注意,clearTimeout()必须在超时持续时间之前调用任何效果即在调用绑定函数之前。其次,在您的情况下,由于图形渲染已经开始,clearTimeout()仅靠它是不够的。

您可以使用某种标志来指示是否应该中止图形渲染操作。

例如:

// 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);
        }
    });
}
于 2013-10-27T13:05:36.443 回答