Search code examples
amcharts4

Draw a moving vertical line representing the current date in amcharts gantt chart?


I am using amCharts4 and is able to plot a vertical line on my Gantt chart representing the current date time as described in the following : Draw a vertical line representing the current date in amcharts gantt chart?. However, how do I make the vertical line move every sec on the chart based on the current time? Here is the code :

var range = dateAxis.axisRanges.create();
range.date = new Date("2020-10-29 07:04:56");
range.grid.stroke = am4core.color("red");
range.grid.strokeWidth = 2;
range.grid.strokeOpacity = 1;

Solution

  • You can add a setInterval that runs every second to update the date on your range, like this:

    // First, create your range marker
    var range = dateAxis.axisRanges.create();
    range.grid.stroke = am4core.color("red");
    range.grid.strokeWidth = 2;
    range.grid.strokeOpacity = 1;
    range.date = new Date();
    
    // Then, update the position of your range marker every second
    range.date = new Date(2018, 0, 1, 8, 0, 0, 0);
    var timeout = window.setInterval(() => {
      range.date = new Date(range.date.getTime() + 1000);
    }, 1000);
    
    chart.events.on('beforedisposed', () => {
       clearTimeout(timeout);
    });
    

    Here is an example

    UPDATE

    One thing you want to do with the timeout is to also clear it when you no longer need it--- for example, when you dispose the chart or the marker.

    I have updated the code above to clear it before the chart is disposed.