1

In the code below you can see async functions, first one to fetch some data, and the second is to build a graph with data that have just been fetched. It works perfectly but I would like to refresh the data each second. I have put setInterval everywhere but nothing works...

Here is the code:

chartSet();

const xAxis = [];
const yAxis = [];

async function resetChart() {
  const datas = await fetch(
    "https://canvasjs.com/services/data/datapoints.php"
  );
  const datasJson = await datas.json();
  datasJson.forEach((elt) => {
    xAxis.push(elt[0]);
    yAxis.push(elt[1]);
  });
}

async function chartSet() {
  await resetChart().catch(() => {
    console.warn("Didn't work");
  });
  const ctx = document.getElementById("myChart3").getContext("2d");
  const myChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: xAxis,
      datasets: [
        {
          label: "Random datas",
          data: yAxis,
          backgroundColor: "rgba(255, 99, 132, 0.2)",
          borderColor: "rgba(255, 99, 132, 1)",
          borderWidth: 1,
        },
      ],
    },
    options: {
      scales: {
        yAxes: [
          {
            ticks: {
              beginAtZero: true,
            },
          },
        ],
      },
    },
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js" integrity="sha512-d9xgZrVZpmmQlfonhQUvTR7lMPtO7NkZMkA0ABN3PHCbKA5nqylQ/yWlFAyY6hYgdF1Qh6nYiuADWwKB4C2WSw==" crossorigin="anonymous"></script>
<canvas id="myChart3"></canvas>

Thank you for your help!

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Simon
  • 209
  • 4
  • 12

2 Answers2

1

You had some kinks with your js. Try this:

setInterval(resetChart, 1000)

const xAxis = [];
const yAxis = [];

async function resetChart() {
  fetch("https://canvasjs.com/services/data/datapoints.php")
    .then(data => data.json(), error => console.warn("Didn't work"))
    .then(dataList => {
      dataList.forEach(elt => {
        xAxis.push(elt[0]);
        yAxis.push(elt[1]);
        chartSet()
      })
    })
}




async function chartSet() {
  const ctx = document.getElementById("myChart3").getContext("2d");
  const myChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: xAxis,
      datasets: [{
        label: "Random datas",
        data: yAxis,
        backgroundColor: "rgba(255, 99, 132, 0.2)",
        borderColor: "rgba(255, 99, 132, 1)",
        borderWidth: 1,
      }, ],
    },
    options: {
      animation: {
        duration: 0
      },
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true,
          },
        }, ],
      },
    },
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js" integrity="sha512-d9xgZrVZpmmQlfonhQUvTR7lMPtO7NkZMkA0ABN3PHCbKA5nqylQ/yWlFAyY6hYgdF1Qh6nYiuADWwKB4C2WSw==" crossorigin="anonymous"></script>
<canvas id="myChart3" style="pointer-events:none"></canvas>

Note that I had to disable pointer events on the canvas, because some kind of skipping error was showing up in the Chart.js jquery itself. I also disabled the chart animation, since it looked a bit annoying after the first time.

Endothermic_Dragon
  • 1,147
  • 3
  • 13
  • Thanks for your answer both of you! However when i try both of your code the result is the same, it refresh each second the graph but the datas are still the same. It feels like it's only refreshing the interface but not the datas it self. – Simon Mar 10 '21 at 13:50
1

Working code:

chartSet();

let xAxis = [];
let yAxis = [];

let timeout = null;

async function resetChart() {
  const datas = await fetch(
    "https://canvasjs.com/services/data/datapoints.php?" + Math.random()
  );
  const datasJson = await datas.json();
  xAxis = [];
  yAxis = [];
  datasJson.forEach((elt) => {
    xAxis.push(elt[0]);
    yAxis.push(elt[1]);
  });
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    chartSet();
  }, 1000);
}

async function chartSet() {
  await resetChart().catch(() => {
    console.warn("Didn't work");
  });
  const ctx = document.getElementById("myChart3").getContext("2d");
  const myChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: xAxis,
      datasets: [{
        label: "Random datas",
        data: yAxis,
        backgroundColor: "rgba(255, 99, 132, 0.2)",
        borderColor: "rgba(255, 99, 132, 1)",
        borderWidth: 1,
      }, ],
    },
    options: {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true,
          },
        }, ],
      },
    },
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js" integrity="sha512-d9xgZrVZpmmQlfonhQUvTR7lMPtO7NkZMkA0ABN3PHCbKA5nqylQ/yWlFAyY6hYgdF1Qh6nYiuADWwKB4C2WSw==" crossorigin="anonymous"></script>
<canvas id="myChart3"></canvas>
jzProg
  • 279
  • 1
  • 2
  • 8
  • Thanks for your answer both of you! However when i try both of your code the result is the same, it refresh each second the graph but the datas are still the same. It feels like it's only refreshing the interface but not the datas it self. – Simon Mar 10 '21 at 13:56
  • @Simon I think you should reset the 2 axis after each data fetch. I edited my answer. – jzProg Mar 10 '21 at 14:42
  • Also, i'm sending a random id on each request in order to return different data (disable cache) – jzProg Mar 10 '21 at 14:57
  • Thank you very much, everything is working fin now! – Simon Mar 11 '21 at 14:51