这是绘制实时图形的代码。它根据概率进行绘制。我想在满足条件后立即退出图形的绘制。
<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>
该图是连续绘制的。有没有办法停止动态图? 当条件满足并遇到警报时如何停止绘图?
谢谢。
答案 0 :(得分:1)
您的图表通过setInterval每秒更新一次:
setInterval(function(){updateChart()}, updateInterval);
您可以使用clearInterval“取消设置”此间隔,但是您需要为此设置间隔ID,该ID是通过setInterval获得的:[1]
var intervalId = setInterval( updateChart, updateInterval );
然后,当您的条件为true时(签入updateChart):
clearInterval( intervalId );
[1]有关clearInterval的更多信息:https://www.w3schools.com/jsref/met_win_clearinterval.asp