Start / Stop Live Chart on Button Click - CanvasJS Javascript Charts

Start / Stop Live Chart on Button Click - CanvasJS Javascript Charts

by canvasjs

HTML

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/><!-- Just so that JSFiddle's Result label doesn't overlap the Chart -->
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
<br/>
<button id="submitStartButton" type="submit" value="Start">Start Live Chart</button>
<button id="submitStopButton" type="submit" value="Stop">Stop Live Chart</button>

CSS

#submitStartButton {
    background-color: #008CBA;
    border: none;
    color: white;
    padding: 12px 20px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
}

#submitStopButton {
    background-color: #f44336;
    border: none;
    color: white;
    padding: 12px 20px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
}

JavaScript

var dps = [{x: 1, y: 15}, {x: 2, y: 20}, {x: 3, y: 18}, {x: 4, y: 22}, {x: 5, y: 20}];   //dataPoints. 
 
var chart = new CanvasJS.Chart("chartContainer",{
	title :{
		text: "Live Data"
	},
	axisX: {						
		title: "Axis X Title"
	},
	axisY: {						
		title: "Units"
	},
	data: [{
		type: "line",
		dataPoints : dps
	}]
});
 
chart.render();

// Updating the Chart
var xVal = dps.length + 1;
var yVal = 20;	
var updateInterval = 1000;
 
var updateChart = function () {
		yVal = yVal +  Math.round(5 + Math.random() *(-5-5));
		dps.push({x: xVal,y: yVal});
		xVal++;
	chart.render();		
};


var timeoutId,
  startButton = document.getElementById('submitStartButton'),
  stopButton = document.getElementById('submitStopButton');

function startLiveChart() {
	timeoutId = setInterval(function(){updateChart()}, updateInterval);
  startButton.removeEventListener('click', startLiveChart);
  stopButton.addEventListener('click', stopLiveChart);
}

function stopLiveChart() {
	clearTimeout(timeoutId);
  stopButton.removeEventListener('click', stopLiveChart);
  startButton.addEventListener('click', startLiveChart);
}  

startButton.addEventListener('click', startLiveChart);