I was creating a real time Chart Data Visualization Using Vue and Socket.io, while following this guide. I have set up a server in Node and express which emits an event through a Socket.io connection every 10 seconds containing a random number, which I listen to in my Vue app and display the number in charts. I am using ChartJS 2.7.1, a Vue-ChartJS wrapper. My server code is:
const io = require('socket.io')(server, {cors: {origin: "*"}});
function getRandomValue(){
return Math.floor(Math.random()*3 + Math.random()*7)
}
io.on('connection', socket=>{
setInterval(()=>{
socket.broadcast.emit("newdata", getRandomValue())
console.log('emitted')
}, 10000)
})
I have opened up a connection in my Vue app which listens to the 'newdata' event.'
getRealtimeData() {
socket.on("newdata", (fetchedData) => {
const d = new Date();
this.dataset1.push(fetchedData);
let date = `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
this.labelLine.push(date);
this.fillData();
});
fillData() is the method in which the chart options and data and labels are configured.
Therefore, my chart should get updated with new data every 10 seconds, when it gets the newdata event, but it happens very frequently(new data is rendered on the chart every 2-3 seconds) and the rate of data coming from the server is also not uniform(sometimes the gap is 5-6 seconds, and sometimes its almost instantaneous. I have attached a screenshot of my chart(and my x-axis contains the time at which the data is plotted on the chart):
As it is seen from the x-axis values, the data comes randomly, sometimes 4-5 times every second. Even if I change the setInterval timeout value in my server.js, nothing changes. Why does this happen? Any help is greatly welcome.
Suggestion: 1.- Don't use socket.io for this approach, you can use SSE . 2.- did you try chart.update() ?, you can push new points but you needs to update the chart so you can see the results, for adding new data just use "update" function as you can see here (using chart.js), let me know if it works for you so i can create an example for you.