0

I am having an issue with my javascript code running on a web page.

I am having 1 chart using d3.js that is updating over time. the data are refreshed every 500ms to update the data of the chart using ajax. My problem is that, when the data getting fetch takes a bit too long, it is getting laggy as i need to set async to off if I want to get my array of data properly.

here is the code

document.addEventListener("DOMContentLoaded", function() {
timer = window.setInterval(updateData, interval);
....
});
function updateData() {
  realTimeData=datafetch();
....
d3.select("#chart").datum(lineArr).call(chart);
}
function datafetch(LastTime) {
var rtn
$.ajax({
url: '/ajax/GetNewData',
data: {
   'id': RecordID
},
async: false,
dataType: 'json',
success: function (data) {
   if (data)
   rtn=JSON.parse(data)
}
});

I know the code is a bit messy and I would listen to your comments for sure.

if I activate async, everything is smooth, but my variable realTimeData never gets the array and is always undefined. when async is on, it is a bit laggy everytime the data is fetch as all the js code is stopped waiting for the response from the server.

Does anyone have any hints on how to handle this problem? Or is there any root issue about the chosen technology?

Do you think I should refresh the chart first, then fetch the data, then after 500ms, update the chart again? it would make me loose 500ms or so in the data refreshing, so if there is another possibility, I would be happy to get some clues.

thank you,

Tibibs
  • 71
  • 1
  • 8
  • 1
    So you update the table inside of the success callback.... Updating every 500ms.... hopefully your site can handle that – epascarello Dec 10 '20 at 13:58
  • This is the exact reason why you should never use `async: false` and why it is deprecated. – Ivar Dec 10 '20 at 13:58
  • You might be interested in the [WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API). – Ivar Dec 10 '20 at 14:00
  • sorry for the delays, I have been pretty busy in this period. @epascarello , I am vairly new to ajax and any js to be honest. What is wrong with that? for the ressources, I am not too worried, the website is hosted locally on a single board computer, and 1 or 2 clients max are connected at a time – Tibibs Dec 28 '20 at 06:20
  • @Ivar , yes on the long run, web sockets are way more appropriate for this but this would mean a lot of changes in the server. my website is running on django, and I would need to update a fair amount of code and learn for some hours in order to switch to socket connection. At the time being, I am looking at a not so terrible solution even if not perfect. I managed at the moment to delay the remaining code by 100 ms. if the response is longer, I just get an empty object and it will be refreshed at the next update – Tibibs Dec 28 '20 at 06:26

0 Answers0