0

Here's a script that fetches data for a chart and repeats the operation every 30 seconds. Problem is that there's a memory leak and some research tells me that I need to add a JavaScript closure. However, since I'm not very familiar to JavaScript, I'm failing to get it working.

Here's the result of my last attempt:

fetch('log_chart.txt')
    .then(function (response) {
        return response.text();
    })
    .then(function (text) {
        let series = csvToSeries(text);
        renderChart(series);
    setTimeout(trigger, 30000);
    })
    .catch(function (error) {
        console.log(error);
    });

  function trigger() {
    setTimeout(function (){
      fetch('log_chart.txt')
      .then(function (response) {
      return response.text();
      })
      .then(function (text) {
      let series = csvToSeries(text);
      renderChart(series);
      })
        .catch(function (error) {
      console.log(error);
    }, 30000);
    });
  }

The first part gets the data and renders the chart, also sets it to repeat after 30 seconds. The second part should repeat the above and it should never stop.

Problem is that it does stop after second update - so the second setTimeout isn't working as I'd expect.

How should I do it instead?

Kalaloom
  • 3
  • 1

1 Answers1

0

In this case, you should use setInterval instead, which runs a certain function every x amount of seconds. It should also solve your memory leak problem, which can be caused by the use of setTimeout, as it is async, meaning that the code continues to add more and more setTimeout while still running other code. This holds up unnecessary memory. More about that here: How does setTimeout() create a memory leak in this code?

As for the solution:

function trigger() {
    fetch("log_chart.txt")
        .then(function (response) {
            return response.text();
        })
        .then(function (text) {
            let series = csvToSeries(text);
            renderChart(series);
        })
        .catch(function (error) {
            console.log(error);
        });
}

trigger()
setInterval(trigger, 30000)

Kenneth Lew
  • 217
  • 3
  • 7