You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AnyChart Gantt定时刷新内存持续增长,求正确数据刷新方案

问题分析与解决方案

当前写法的问题

  • 每次调用init_schedule都重复执行anychart.onDocumentReady,这个事件仅需在页面首次加载时触发一次,重复绑定无实际意义。
  • 每次刷新都创建新的anychart.ganttResource()实例,但未销毁旧实例,直接清空container的innerHTML无法彻底清除图表关联的事件监听、内存引用,导致内存持续泄漏。
  • 1秒一次的高频请求既给服务器施压,也让浏览器频繁处理图表创建与渲染,加剧性能消耗。

优化方案

方案1:复用图表实例,仅更新数据

这是解决内存问题的最优方案,避免重复创建图表实例:

// 全局保存图表实例
let chartInstance = null;

function init_schedule() {
    anychart.onDocumentReady(function () {
        // 首次加载时创建图表实例并配置基础样式
        if (!chartInstance) {
            chartInstance = anychart.ganttResource();
            chartInstance.container("container");
            // 在这里设置图表的固定配置(如坐标轴、全局样式等,仅执行一次)
        }

        // 每次刷新仅请求并更新数据
        anychart.data.loadJsonFile("../scheduler?type=getschedule", function (data) {
            const treeData = anychart.data.tree(data, "as-tree");
            chartInstance.data(treeData);
            chartInstance.draw();
        });
    });
}

// 初始化一次
init_schedule();
// 建议延长刷新间隔,减少性能消耗
let intervalId = setInterval(function() {
    init_schedule();
}, 5000);

方案2:必须重建图表时,正确销毁旧实例

如果因业务需求必须每次重建图表,一定要先销毁旧实例释放内存:

let chartInstance = null;

function init_schedule() {
    anychart.onDocumentReady(function () {
        // 销毁旧实例,释放内存
        if (chartInstance) {
            chartInstance.dispose();
            chartInstance = null;
        }

        anychart.data.loadJsonFile("../scheduler?type=getschedule", function (data) {
            const treeData = anychart.data.tree(data, "as-tree");
            chartInstance = anychart.ganttResource();
            chartInstance.data(treeData);
            chartInstance.container("container").draw();
        });
    });
}

let intervalId = setInterval(function() {
    init_schedule();
}, 1000);

额外优化建议

  • 延长定时器间隔:1秒一次的刷新过于频繁,非强业务需求建议改为3-10秒,降低服务器与浏览器压力。
  • 增加请求防抖:避免上一次请求未完成就发起新请求,可通过状态标记实现:
let isRequesting = false;

function init_schedule() {
    if (isRequesting) return;
    isRequesting = true;

    anychart.onDocumentReady(function () {
        anychart.data.loadJsonFile("../scheduler?type=getschedule", function (data) {
            // ... 图表更新逻辑
            isRequesting = false;
        });
    });
}

内容的提问来源于stack exchange,提问作者Pauel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 18:16:12