2013-10-27 34 views
0

我有兩個按鈕應該顯示兩個不同系列的圖表。每一系列圖形逐漸顯示一個在另一個之下,延遲3秒。如果用戶點擊第一個按鈕,他會逐漸顯示第一個系列,如果用戶點擊第二個按鈕,第一個系列將被刪除,第二個系列將逐漸開始逐漸顯示。中斷JQuery setTimeout函數

下面是一段代碼:

<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,然後第二個系列獲得附加。所以正如我udnderstand我需要停止第一次setTimeOut第二次運行與另一個參數。我知道我需要使用

clearTimeout(timer) 

......但我不知道在哪裏使用它。無論我把它放在哪裏,我都會得到'未知變量計時器'。

+0

問題變量'timer'是本地'$ .getJSON'回調函數... –

+0

你在哪裏使用'clearTimeout(定時器)'? –

+0

它有助於在外面聲明它,然後在函數內部使用它嗎? – user164863

回答

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); 
     } 
    }); 
} 
+0

太棒了!如果'類型'在數量上可能有所不同,即它實際上是從Mysql DB中獲取唯一類型的數據,並顯示帶有這些類型的按鈕,例如那些可以是3到11種類型? – user164863

+0

在這種情況下,您可以運行一個小循環以確保所有其他人都被取消。查看更新。 – techfoobar

+0

看起來很不錯,但那裏出了問題。我已經使用本地日期源jsfiddle,所以可以看到它在某個地方崩潰:http://jsfiddle.net/fbKSa/18/ – user164863