skip to Main Content

I am trying to create a chart in Apexchart that, when a button is clicked, will add a new data every 2 seconds 5 times. My code is as follows:

var salesdata=[30,40,45,50,49,60,70,91,125];
var buysdata=[20,30,45,52,42,33,40,41,65];
var i=0;
var options = {
  chart: {
    type: 'bar'
  },
  series: [{
    name: 'sales',
    data: salesdata,
  },
          {
    name: 'buys',
    data: buysdata,
  }],
  xaxis: {
    categories: [1991,1992,1993,1994,1995,1996,1997, 1998,1999,2000,2001,2002,2003,2004,2005]
  }
}

var chart = new ApexCharts(document.querySelector("#chart"), options);

chart.render();
 

function update(){

  function appendStats(){
    i++;
   

   salesdata.push(salesdata[salesdata.length-1]+22);
   buysdata.push(buysdata[buysdata.length-1]+32);
   chart.appendData([{
     data: 0,
     }])
  if(i===4)
    clearInterval(timerId);
 }


   let timerId=setInterval(appendStats,2000); 
 
 }
@import url(https://fonts.googleapis.com/css?family=Roboto);

body {
  font-family: Roboto, sans-serif;
}

#chart {
  max-width: 650px;
  margin: 35px auto;
}
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<button onclick='update()'>Click me</button>
<div id="chart">
</div>

The problem is that instead of updating one data, waiting for 2 seconds and appending another data. The code waits for 10 seconds and appends the data in one go. How do I fix this? Any help is much appreciated.

2

Answers


  1. Your sleep function can be rewritten to

    function recSleep(timesToRepeat, timeMS) {
      appendStats(); 
      if (timesToRepeat > 1) {
        setTimeout(() => {
           recSleep(timesToRepeat - 1, timeMS)
        }, timeMS);
      }
    }

    Then in your update function call it like recSleep(5, 2000)

    Login or Signup to reply.
  2. To append data to an ApexCharts chart every 2 seconds using JavaScript, you can utilize the window.setInterval() function to schedule a repeated task. Here’s an example:

    First, make sure you have included the necessary ApexCharts library in your HTML file.

    // Create an empty array to store the data points
    var dataPoints = [];
    
    // Create an ApexCharts instance
    var chart = new ApexCharts(document.querySelector("#chart"), {
      series: [{
        name: 'Data',
        data: dataPoints
      }],
      chart: {
        type: 'line',
        height: 350
      },
      xaxis: {
        type: 'datetime',
        labels: {
          format: 'dd/MM/yyyy HH:mm:ss'
        }
      },
    });
    
    // Render the chart
    chart.render();
    
    // Function to append new data to the chart
    function appendData() {
      // Generate a random data point
      var newDataPoint = {
        x: new Date().getTime(),
        y: Math.floor(Math.random() * 100)
      };
    
      // Append the new data point to the array
      dataPoints.push(newDataPoint);
    
      // Limit the array size to a certain number of data points (optional)
      if (dataPoints.length > 20) {
        dataPoints.shift(); // Remove the oldest data point
      }
    
      // Update the chart with the new data
      chart.updateSeries([{
        data: dataPoints
      }]);
    }
    
    // Schedule the appendData function to run every 2 seconds
    var interval = window.setInterval(appendData, 2000);
    <div id="chart"></div>

    In the example above, we create an empty array called dataPoints to store the chart data. We then initialize an ApexCharts instance with the required configuration, including the series object referencing the dataPoints array.

    The appendData function is responsible for generating a new data point, adding it to the dataPoints array, and updating the chart using chart.updateSeries(). In this example, we generate a random y value and use the current timestamp as the x value.

    Finally, we use window.setInterval() to repeatedly call the appendData function every 2 seconds (2000 milliseconds) and update the chart accordingly.

    Note: Make sure to customize the ApexCharts configuration, such as chart type, height, and x-axis format, according to your specific requirements.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search