Search code examples
javascripthtmlcanvasjs

How to stop plotting a live graph on a certain condition using canvas js


This is the code which plots a live graph. It plots on the basis of probability. I want to exit the plotting of the graph as soon as a condition is satisfied.

<script>
window.onload = function () 
{

    var dps = []; // dataPoints
    var chart = new CanvasJS.Chart("chartContainer", {
        title :{
            text: "Dynamic Data"
        },
        axisY: {
            includeZero: false
        },      
        data: [{
            type: "line",
            dataPoints: dps
        }]
    });

    var xVal = 0;
    var yVal = 100; 
    var updateInterval = 1000;
    var dataLength = 20; // number of dataPoints visible at any point
    var weights = [0.7, 0.3]; // probabilities
    var results = [1, 50];//values to plot
    var y=[];
    var updateChart = function (count) 
    {
        count = count || 1;
        for (var j = 0; j < count; j++) 
        {
            yVal =  getRandom();
            y.push(yVal)//push to array y
            dps.push({
                x: xVal,
                y: yVal
            });
            xVal++;
        }

        if (dps.length > dataLength) 
        {
            dps.shift();
        }

        if((y.length>4) && (y[y.length-2]==50) && (y[y.length-1]==50) )//condition to exit
        {
            myFunction();
        }

        chart.render();
    };

    updateChart(dataLength);//function call
    setInterval(function(){updateChart()}, updateInterval);

 // returns 1 or 50 based on probability given above.

    function getRandom () 
    {
        var num = Math.random(),
            s = 0,
            lastIndex = weights.length - 1;

        for (var i = 0; i < lastIndex; ++i) {
            s += weights[i];
            if (num < s) {
                return results[i];
            }
        }

        return results[lastIndex];
    };

    function myFunction() {
        alert("I am an alert box!");//alert and should exit the plot
        //code to be written 
    }

}
</script>

The graph is continuously plotted. Is there a way to stop the dynamic plot? How do I stop the plot when the condition is satisfied and an alert is encountered?

Thanks in advance.


Solution

  • Your chart gets updated once a second by setInterval:

    setInterval(function(){updateChart()}, updateInterval);
    

    You can "unset" this interval with clearInterval, but you need the interval-id for this, which you get by setInterval: [1]

    var intervalId = setInterval( updateChart, updateInterval );
    

    And then, when your condition is true (check in updateChart):

    clearInterval( intervalId );
    

    [1] more information about clearInterval: https://www.w3schools.com/jsref/met_win_clearinterval.asp