user164863
user164863

Reputation: 641

Interrupt JQuery setTimeout function

I have two buttons which supposed to display two different series of graphs. Each series of graphs getting displayed gradually one under the other with 3 seconds delay. If user clicks first button he gradually gets shown first series, if user clicks second button the first series gets deleted and the second series starts to show gradually one by one.

Here is the piece of code:

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

The problem is if user clicks second button before first series completed appending then the div gets cleared but first series continues to append its graps and then second series get appended. So as I udnderstand I need to stop first setTimeOut before running it second time with another parameters. I understand I need to use

clearTimeout(timer)

... but I can't figure out where to use it. Wherever I put it I get 'unknown variable timer'.

Upvotes: 0

Views: 680

Answers (1)

techfoobar
techfoobar

Reputation: 66693

Note that clearTimeout() to have any effect must be called before the timeout duration, i.e. before the bound function is invoked. Secondly, in your case, since the graph rendering would already have started, clearTimeout() alone will not be sufficient.

You can use some kind of flag to indicate whether a graph rendering operation should be aborted or not.

For 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);
        }
    });
}

Upvotes: 2

Related Questions