You need to enable JavaScript to run this app. 如何实现每3秒刷新AnyChart词云div以自动同步最新数据
优惠活动
大模型
产品
解决方案
定价
更多

如何实现每3秒刷新AnyChart词云div以自动同步最新数据

问题原因

你当前的刷新逻辑只是重复复制容器内已有的HTML内容,没有重新请求谷歌表格的最新数据,也没有重新渲染词云实例,自然不会更新内容。

修复方案

把数据拉取、词云渲染的逻辑封装为可重复调用的函数,定时器每次触发时直接调用该函数即可,同时新增旧实例销毁逻辑避免内存泄漏。
修正后的JS代码如下:

// 全局保存图表实例,方便后续销毁
let wordCloudChart = null;

// 封装词云刷新逻辑
function refreshWordCloud() {
  anychart.data.loadGoogleSpreadsheet({
    key: '14jdnD4rzxPdZfLqpeh4gjtoN6ERyZuovBOoFOwuZQAM',
    sheet: '2'
  }, function(data) {
    // 销毁旧的图表实例
    if (wordCloudChart) {
      wordCloudChart.dispose();
    }
    
    wordCloudChart = anychart.tagCloud();

    // 配置颜色比例尺
    var customColorScale = anychart.scales.linearColor();
    customColorScale.colors(["#FEBF57", "#428A46", "#21C5B4", "#E7438A", "#21295E"]);

    // 图表基础配置
    wordCloudChart.colorScale(customColorScale);
    wordCloudChart.colorRange().enabled(true);
    wordCloudChart.normal().fontFamily("Rubik", "sans-serif");

    // 加载新数据并渲染
    wordCloudChart.data(data);
    wordCloudChart.container('wordcloud-container');
    wordCloudChart.draw();
  });
}

// 页面加载完成后执行
anychart.onDocumentReady(function() {
  // 首次渲染词云
  refreshWordCloud();
  // 每3秒刷新一次
  setInterval(refreshWordCloud, 3000);
});

HTML代码无需修改,保持原有结构即可:

<h1>TEST WordCloud with colours</h1>
<div id='wordcloud-container'></div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 16:45:09