停止动态生成的setInterval [英] stopping dynamically generated setInterval

查看:136
本文介绍了停止动态生成的setInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我生成多个图表,每个图表都有自己的setInterval来刷新数据。我已经将它设置为clearInterval当动态生成的容器被删除 - 但是如果我重新加载,并且它具有相同的ID旧setInterval继续运行。有没有办法设置一个动态命名的setInterval,当生成替换时可以停止?



现在我正在使用:

  function generateChart(data,location){
var chart = new Highcharts.Chart({
//等等等等等等等等等) },function(chart){
setInterval(function(){
if($('#'+ location).length){
//我每分钟做的事情
} else {
clearInterval();
}
},60000);
});
}

会发生什么,该位置是一个随机生成的字符串,成为元素ID对于Highchart的容器,如果用户保存图表,它将成为唯一标识符。如果用户更新已保存的图表并重新载入图表,则旧图标将获得.removed(),并在其位置生成新图表。现在,新元素具有与旧元素相同的元素ID,并且由于旧时间间隔发现它想要的容器,它会尝试继续更新 - 这是因为它的图表变得流畅。



有没有办法设置一个动态变量我可以使用setInterval,以便我可以clearInterval吗?

  var blob + location = setInterval(function(){... 

然后

  clearInterval(blob + location); 


<您可以使用一个对象:

  var myObj => 

{};

var location =somevalue;

myObj [位置] = setInterval(...

clearInterval(myObj [location] );


I am generating multiple charts each with their own setInterval to refresh the data. I have it set to clearInterval when the dynamically generated container is removed - but if I reload and it has the same id the old setInterval continues to run. Is there a way to set a dynamically named setInterval that can be stopped when the replacement is generated?

Right now I'm using:

function generateChart(data, location){
    var chart = new Highcharts.Chart({
        // blah blah blah
    }, function(chart){
        setInterval(function(){
            if($('#'+location).length){
                // I'm doing stuff every minute
            }else{
                clearInterval();
            }
        },60000);
    });
}

What happens is, the location is a randomly generated string that becomes the element ID for the container for the Highchart and if they user saves the chart it becomes the unique identifier. If the user updates the chart that's saved and reloads the chart, the old one gets .removed() and the new one generated in its place. Now the new one has the same element ID as the old one and since the old interval finds the container it wants it attempts to continue updating - which is can't since its chart went poof.

is there a way to set a dynamic variable I can use for setInterval so that I can clearInterval on it?

var blob+location = setInterval(function(){ ...

and then

clearInterval(blob+location);

解决方案

You can just use an object:

var myObj = {};

var location = "somevalue";

myObj[location] = setInterval(...

clearInterval(myObj[location]);

这篇关于停止动态生成的setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆