首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Interrupt JQuery setTimeout函数

Interrupt JQuery setTimeout函数
EN

Stack Overflow用户
提问于 2013-10-27 20:55:59
回答 1查看 630关注 0票数 0

我有两个按钮,这两个按钮应该显示两个不同的图形系列。每一系列图形逐渐显示,一个接一个,延迟3秒。如果用户单击第一个按钮,他将逐渐显示第一个系列,如果用户单击第二个按钮,第一个系列将被删除,第二个系列开始逐个逐渐显示。

下面是这段代码:

代码语言:javascript
复制
<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之前,我需要先停止它。我知道我需要用

代码语言:javascript
复制
clearTimeout(timer)

..。但是我不知道该在哪里使用它。无论我把它放在哪里,我都会得到‘未知变量定时器’。

EN

回答 1

Stack Overflow用户

发布于 2013-10-27 21:05:36

请注意,必须在超时持续时间之前调用clearTimeout()才能生效,即在调用绑定函数之前。其次,在您的例子中,由于图形渲染已经开始,仅有clearTimeout()是不够的。

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

对于ex:

代码语言:javascript
复制
// 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);
        }
    });
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19618279

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档