【问题标题】:stop loop from setInterval when click is done单击完成时从 setInterval 停止循环
【发布时间】:2018-06-23 18:17:39
【问题描述】:

我需要你们的帮助或建议来修复或更改我的 js 脚本。 问题是当我点击一些按钮来更改 json 文件时(这个文件在函数 setinterval 内运行 1 秒),请求成倍增加,目标只是在点击时选择的最后一个文件中设置 setinterval。 我创建了一个临时解决方案,但我知道这是不正确的。出于这个原因,我写了这个线程。 我发现停止循环的解决方案是在 setinterval 之前放置 clearInterval(reload) 函数,但这是错误的,因为 reload var 在 clearInterval 之后运行。

我把我的脚本放在这里。也许有人可以帮助找到停止循环的解决方案。

循环问题:http://sc.sny.pt/sUUL

脚本:https://jsfiddle.net/hj0dp7ng/

function drawHighchart(timeFramUrl) {
    $.ajax({url: timeFramUrl, success: function(data){

        var currentValue = (data[data.length - 1][1]);

        Highcharts.chart('container', {

        chart: {
          zoomType: 'x',
          events: {
            load: function() {
              var series = this.series[0];
              var chart  = this;
              var yAxis  = chart.yAxis[0],
                           plotLine,
                           d,
                           newY;

              yAxis.addPlotLine({
                value: currentValue,
                color: 'green',
                width: 2,
                zIndex: 5,
                id: 'plot-line-1',
                label: {
                    text: currentValue + 'EUR',
                    align: 'left',
                      style: {
                        color: 'green',
                      },
                    y: -4,
                    x: 0
                }
              });

             // Is this correct ????
             // Stop loop when click in buttons <min> , <hour> , <day> or <forever>
             
              //clearInterval(reload); 

              reload = setInterval(function() {

                $.getJSON(timeFramUrl, function(recData) {
                    
                  var currentValue = (recData[recData.length - 1][1]); 
                  var currenttime  = (recData[recData.length - 1][0]);

                  series.setData(recData);

                  var x = currenttime,
                      y = currentValue;

                  series.addPoint([x, y], true, true);    

                  plotLine  = yAxis.plotLinesAndBands[0].svgElem;
                  d         = plotLine.d.split(' ');
                  newY      = yAxis.toPixels(y) - d[2];
                  plotlabel = yAxis.plotLinesAndBands[0].label;

                  plotlabel.animate({
                  translateY: newY,
                  text: Highcharts.numberFormat(y, 2)
                  }, {
                    duration: 400,
                    step: function() {
                      $(this.element).html(y + 'EUR');
                    },
                    complete: function() { }
                  }),


                  plotLine.animate({
                    translateY: newY
                  }, 400);

                });

              }, 1000);


            }
          }
    },  
        title:         { text:        ''},
        exporting:     { enabled: false },
        credits:       { enabled: false },
        xAxis:         { type: 'datetime'},
        yAxis:         { opposite: true,
                         labels: {
                            align: 'left',
                         },
                         gridLineWidth: 0, 
                         title: {
                            text: 'Exchange rate'
                        }, 
        },
        plotOptions: {
          areaspline: { 
            marker: {
              enabled: false
            }
          }
        },
        series: [{
            name: 'Exchange BTC to EUR',
            data: data,
            type: 'areaspline',
            threshold: null,
            animation: true,
            tooltip: {
                valueDecimals: 2
            },
            fillColor: {
                linearGradient: { x1: 5, y1: 0, x2: 0, y2: 0
            },
            stops: [ [0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] ]
            }
        }]
    });
    }});
}

$(document).ready(function() {
    var selectedTimeFrameUrl = null;
    var srcURL = $("#hour").data( "url" );
    drawHighchart(srcURL);
    $("#min, #hour, #day, #forever").click(function(){
        var srcURL = $(this).data( "url" );
        drawHighchart(srcURL);
    });
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<!-- Bottons to change the json file -->

<button id="min" data-url="https://api.myjson.com/bins/15v8km">Month</button>
<button id="hour" data-url="https://api.myjson.com/bins/inbza">Day</button>
<button id="day" data-url="https://api.myjson.com/bins/dafja">Hour</button>
<button id="forever" data-url="https://api.myjson.com/bins/psj8m">Hour</button>


<div id="container" style="height: 400px; width: 100%"></div> 

【问题讨论】:

标签: javascript html


【解决方案1】:

试试这个我只添加class="stop_button"到所有按钮和下面的功能

 $(".stop_button").click(function(){
       clearInterval(reload); 
  });

function drawHighchart(timeFramUrl) {
    $.ajax({url: timeFramUrl, success: function(data){

        var currentValue = (data[data.length - 1][1]);

        Highcharts.chart('container', {

        chart: {
          zoomType: 'x',
          events: {
            load: function() {
              var series = this.series[0];
              var chart  = this;
              var yAxis  = chart.yAxis[0],
                           plotLine,
                           d,
                           newY;

              yAxis.addPlotLine({
                value: currentValue,
                color: 'green',
                width: 2,
                zIndex: 5,
                id: 'plot-line-1',
                label: {
                    text: currentValue + 'EUR',
                    align: 'left',
                      style: {
                        color: 'green',
                      },
                    y: -4,
                    x: 0
                }
              });

             // Is this correct ????
             // Stop loop when click in buttons <min> , <hour> , <day> or <forever>
             
              //clearInterval(reload); 
               reload = setInterval(function() {

                $.getJSON(timeFramUrl, function(recData) {
                    
                  var currentValue = (recData[recData.length - 1][1]); 
                  var currenttime  = (recData[recData.length - 1][0]);

                  series.setData(recData);

                  var x = currenttime,
                      y = currentValue;

                  series.addPoint([x, y], true, true);    

                  plotLine  = yAxis.plotLinesAndBands[0].svgElem;
                  d         = plotLine.d.split(' ');
                  newY      = yAxis.toPixels(y) - d[2];
                  plotlabel = yAxis.plotLinesAndBands[0].label;

                  plotlabel.animate({
                  translateY: newY,
                  text: Highcharts.numberFormat(y, 2)
                  }, {
                    duration: 400,
                    step: function() {
                      $(this.element).html(y + 'EUR');
                    },
                    complete: function() { }
                  }),


                  plotLine.animate({
                    translateY: newY
                  }, 400);

                });

              }, 1000);


            }
          }
    },  
        title:         { text:        ''},
        exporting:     { enabled: false },
        credits:       { enabled: false },
        xAxis:         { type: 'datetime'},
        yAxis:         { opposite: true,
                         labels: {
                            align: 'left',
                         },
                         gridLineWidth: 0, 
                         title: {
                            text: 'Exchange rate'
                        }, 
        },
        plotOptions: {
          areaspline: { 
            marker: {
              enabled: false
            }
          }
        },
        series: [{
            name: 'Exchange BTC to EUR',
            data: data,
            type: 'areaspline',
            threshold: null,
            animation: true,
            tooltip: {
                valueDecimals: 2
            },
            fillColor: {
                linearGradient: { x1: 5, y1: 0, x2: 0, y2: 0
            },
            stops: [ [0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] ]
            }
        }]
    });
    }});
}

$(document).ready(function() {
    var selectedTimeFrameUrl = null;
    var srcURL = $("#hour").data( "url" );
    drawHighchart(srcURL);
    $("#min, #hour, #day, #forever").click(function(){
        var srcURL = $(this).data( "url" );
        drawHighchart(srcURL);
    });
});
 $(".stop_button").click(function(){
          clearInterval(reload); 
    });
       
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<!-- Bottons to change the json file -->

<button id="min" data-url="https://api.myjson.com/bins/15v8km" class="stop_button">Month</button>
<button class="stop_button" id="hour" data-url="https://api.myjson.com/bins/inbza">Day</button>
<button class="stop_button" id="day" data-url="https://api.myjson.com/bins/dafja">Hour</button>
<button class="stop_button" id="forever" data-url="https://api.myjson.com/bins/psj8m">Hour</button>


<div id="container" style="height: 400px; width: 100%"></div> 

我希望你得到你需要的东西

【讨论】:

  • "clearInterval(reload)" 在"var reload" 之前没有问题吗?
  • 是的,这种方式可行,但我认为这不是正确的解决方案,因为“clearInterval(reload)”在“var reload”之前。
  • 在 js 中定义变量的位置无关紧要,因为 js 是基于自下而上的方法。你只关心关闭。
  • @manan5439 但这不是真的。在这种情况下它起作用的原因是因为 var 正在被提升。如果您使用的是letconst(您应该这样做),那么它将无法正常工作。
  • 是的,我知道在 ecma script6 之后
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-15
  • 1970-01-01
  • 1970-01-01
  • 2022-11-28
  • 2014-12-31
  • 1970-01-01
相关资源
最近更新 更多