0
votes

I need some help or suggestions from your guys to fix or change my js script. The problem is when I click in some buttons to change the json file (this file is inside function setinterval running 1 in 1s), the requests multiply, the goal is only make setinterval in the last file selected on click. I create a temporarily solution, but I know that is not the correct. for that reason im writing this thread. The solution I found to stop loop is put clearInterval(reload) funtion before setinterval, but thats wrong because reload var is running after the clearInterval.

I put here my script. maybe someone can help find a solution to stop the loop.

Loop issue: http://sc.sny.pt/sUUL

Script: 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> 
1

1 Answers

0
votes

try this i only add class="stop_button" to all button and below function

 $(".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> 

i hope you got as you need