Skip to content
Advertisement

javascript update view if value change

i have java script where im getting value from websocets server, is updating the view every 1 sec , i will like to have the view only to be updated when the value change (add new point on the chart ), as for now is updating every time even if the value is the same,

    <script>
var chartT = new Highcharts.Chart({
  chart:{ renderTo : 'chart-temperature' },
  title: { text: 'Module Voltage' },
  series: [{
    showInLegend: false,
    data: []
  }],
  plotOptions: {
    line: { animation: false,
      dataLabels: { enabled: true }
    },
    series: { color: '#059e8a' }
  },
  xAxis: { type: 'datetime',
    dateTimeLabelFormats: { second: '%H:%M:%S' }
  },
  yAxis: {
    title: { text: 'Voltage (V)' }
    //title: { text: 'Temperature (Fahrenheit)' }
  },
  credits: { enabled: false }
});
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var x = (new Date()).getTime(),
          y = parseFloat(this.responseText);
      //console.log(this.responseText);
      if(chartT.series[0].data.length > 40) {
        chartT.series[0].addPoint([x, y], true, true, true);
      } else {
        chartT.series[0].addPoint([x, y], true, false, true);
      }
    }
  };
  xhttp.open("GET", "/temperature", true);
  xhttp.send();
}, 1000 ) ;


</script>

Advertisement

Answer

Keeping only the interval code here.

So if you are using websocket library such as socket.io then you can update the view when the socket emit event irrespective of the previous and current value.

While you are using the plain api call here and you wish to update the value only when data changes and you have called setInterval that will call after every 1 second. Than it will be good to store the value in json object and validate the changes.

Such as below I have initialized a json object name change as {}. So the view will be updated or position will be rendered only when there are change in x and y.

<script>
const change = {};
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var x = (new Date()).getTime(),
          y = parseFloat(this.responseText);
      if (!change[`${y}`]) {
           if(chartT.series[0].data.length > 40) {
             chartT.series[0].addPoint([x, y], true, true, true);
         } else {
            chartT.series[0].addPoint([x, y], true, false, true);
        }
        change[`${y}`] = true;
      }
     
    }
  };
  xhttp.open("GET", "/temperature", true);
  xhttp.send();
}, 1000 ) ;


</script>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement