最近在写数据可视化,长期跑在大屏上,但是总会遇到浏览器崩溃的问题,最终发现是定时器刷新加载函数,重复创建echarts示例的原因,不清空会一直占内存,导致超出浏览器堆内存页面崩溃,下面是测试可以看到内存一直再增加。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
div {
width: 500px;
height: 500px;
}
</style>
<body>
<div id="main">
</div>
</body>
<script src="./src/js/ins/echarts.min.js"></script>
<script>
function chart() {
var chartDom = document.getElementById('main');
myChart = echarts.init(chartDom);
var option;
option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
};
option && myChart.setOption(option);
}
setInterval(() => {
chart()
}, 1);
</script>
</html>
解决方法:echarts的销毁函数dispose()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
div {
width: 500px;
height: 500px;
}
</style>
<body>
<div id="main">
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.2.1/dist/echarts.min.js"></script>
<script>
//我在这
var myChart = null;
function chart() {
//我在这
if (myChart) {
myChart.dispose(); // 销毁之前的 ECharts 实例
}
var chartDom = document.getElementById('main');
myChart = echarts.init(chartDom);
var option;
option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
};
option && myChart.setOption(option);
}
setInterval(() => {
chart()
}, 1);
</script>
</html>