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
Your sleep function can be rewritten to
Then in your
update
function call it likerecSleep(5, 2000)
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.
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.