1

I'm trying to add a Plotly chart to my webpage. The data is being sent to Javascript through SocketIO, but the chart is empty.

I don't understand why, since the data is being pushed to arr. Any advice?

var arr = [];

socket.on('two', function(msg) {

    arr.push(msg.num)

    console.log(arr)
  });

  Plotly.plot('chart',[{
      y:[0],
      type:'line'
    }]);

    var cnt = 0;
    setInterval(function(){
        Plotly.extendTraces('chart',{ y:[[arr]]}, [0]);
        cnt++;
        if(cnt > 500) {
            Plotly.relayout('chart',{
                xaxis: {
                    range: [cnt-500,cnt]
                }
            });
        }
    },15);
Shahnewaz
  • 360
  • 4
  • 12
Jack022
  • 867
  • 6
  • 30
  • 91
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Nov 24 '18 at 18:17

1 Answers1

1

The Socket.io on() function is asynchronous. Thus, the Plotly code is not waiting on it to finish and, as such, only receives an empty array as its data. Try instantiating your Plotly graph before making your remote data request through Socket.io then update the graph in the response function of the on() method.

Matt Morse
  • 139
  • 1
  • 5