关于#echarts#,暂停后点击继续按钮数据重新渲染的问题,如何解决?

#我在用echarts来做一个柱状的动态排序图,更新数据是用的一个setTimeout来更新,但是我想设置开始和暂停两个按钮,暂停之后柱状图的数据开始重新渲染,我该怎么办?
第一次提问,不太熟练,怕老哥们看不全,所以关于echarts配置项的代码也放上去了,有关更新数据的代码在代码尾部

img


```javascript
    <div id="main" style="width: 100%; height: 100%">div>
    <button class="start" onclick="updateepic();">开始button>
    <button class="zt" onclick="delay()" >暂停button>
        <script src='map/js/china.js'>script>
   <script>
    
        
        
   var chartDom = document.getElementById('main');
   var myChart = echarts.init(chartDom);
   const updateFrequency = 100;//值越小更新速度越快
    var countryColors = {
    
    //这里配置颜色  选择一种合理的色彩搭配 网上找那种配色网站做参考
         '上海':'#49A902',
         '云南':'#BB0B52',
         '内蒙古':'#B4837E',
         '北京':'#404c4c',
         '台湾':'#fc4839',         
         '吉林':'#681408',
         '四川':'#E8858A',
         '天津':'#366D72',
         '宁夏':'#216F94',
         '安徽':'#7a8285',
         '山东':'#929a9c',
         '山西':'#E81EDB',          
         '广东':'#ed685f',          
         '广西':'#EA90C3',
         '新疆':'#89a3c8',
         '江苏':'#C1A2C8',
         '江西':'#a2ba98',
         '河北':'#99CCD5',
         '河南':'#456ca5',
         '浙江':'#3ed0bb',
         '海南':'#CF3D37',
         '湖北':'#fd0208',
         '湖南':'#BCD79B',
         '澳门':'#33DCC9',
         '甘肃':'#13DE4B',
         '福建':'#33E800',
         '西藏':'#CDF500',
         '贵州':'#0299D0',
         '辽宁':'#6F378C',
         '重庆':'#CEA014',
         '陕西':'#30D568',
         '青海':'#C6353A',
         '香港':'#1E1280',
         '黑龙江':'#718cb9',
    };

$.getJSON("data/yiqingdata.json",function (res) {



    let arr = Object.values(res);
    for(let i = 0;ilength;i++){
        arr[i].count_confirm=Number(arr[i].count_confirm);
    }
    let arr1 = [];
    for (let i = 0;ilength;i++){
        arr1.push(Object.values(arr[i]));
    }
    arr1 = arr1.reverse();
    let dates = [];
         for(var i=0;ilength;i++){
                dates.push(arr[i].riqi);
        }
        //去重函数,输入数组
    function removeDuplicate(arr) {
          const newArr = []
          arr.forEach(item => {
            if (newArr.indexOf(item) === -1) {
              newArr.push(item)
            }
          })
          return newArr // 返回一个新数组
        }
        dates = removeDuplicate(dates).reverse();


    let startIndex = 0;
    let startDate = dates[startIndex]; 
    option = {

      visualMap: {
      type: 'piecewise',
      pieces: [{
          min: 500001,
          color: '#73240D'
      },
      {
          min: 100001,
          max: 500000,
          color: '#BB0000'
      },
      {
          min: 10001,
          max: 100000,
          color: '#BD430A'
      },
      {
          min: 1001,
          max: 10000,
          color: '#E08150'
      },
      {
          min: 101,
          max: 1000,
          color: '#E9B090'
      },
      {
          min: 1,
          max: 100,
          color: '#F2DDD2'
      },
      {
          value: 0,
          color: 'white'
      }
      ],
      orient: 'vertical',
      itemWidth: '20%',
      itemHeight: '15%',
      showLabel: true,
      seriesIndex: [0],
      text: ["高", "低"],
      textStyle: {
          color: '#7B93A7'
      },
      bottom: '10%',
      right: "20%",
                 },
    tooltip:[{
        formatter:'{b}',
        seriesIndex: [0],
    },
    ],                    
                        
                        
    
        //坐标系底板
        grid: [{
             left: '5%',
             top: '10%',
             bottom: '10%',
             width: '50%',
        },
        {
                right: '5%',
                top: '20%',
                bottom: '75%',//应该去了
                width: '0%'
        }
        ],
        //x坐标轴
        xAxis: [{
            splitLine:{
                show:false,
            },
            max: "dataMax", //x坐标轴刻度最大值为数据的最大值
            axisLabel: { //坐标轴刻度标签的相关设置
                formatter: function (n) {
                    return Math.round(n) + ""; //刻度取整数
                },
            show:false,
            
            },

        },{
            gridIndex: 1
        }
        ],
        //初始数据集
        dataset: [{
            source: arr1.filter(function (d) {
                return d[0] === startDate;
            }),
        },{
            
        }],
        //y坐标轴
        yAxis: [{
            type: "category", //类目轴
            inverse: true, //是否反向坐标轴
            max: 10, //因为y是类目轴,所以这里指的是类目的序数,也就是只显示前11个类目,从0开始计数
            axisLabel: {
                show: true,
                fontSize: 14,
                //设置y轴字体格式
                //formatter: function (value) {
                //    //原本标签值加上缩写,flag| 表示缩写采用rich中的flag定义的样式
                //    return value + "{flag|" + getFlag(value) + "}";
                // },
                rich: { //定义富文本样式
                    flag: {
                        fontSize: 25,
                        padding: 5,
                    },
                },
            },

            animationDuration: 300,
            animationDurationUpdate: 300,
        },
        {
                      inverse: false,
          offset: '2',
          'type': 'category',
          nameTextStyle: {
              color: '#000'
          },
          axisTick: {
              show: false,
          },
          axisLabel: {
              //rotate:45,
              show: false,
              textStyle: {
        
                  color: '#000000',
              },
              interval: 'auto'
          },
          axisLine: {
              show: false,
              lineStyle: {
                  color: '#333'
              },
          },
          splitLine: {
              show: false,
              lineStyle: {
                  color: '#333'
              }
          },
          gridIndex: 1
        }
        ],


        //系列
        series: [
              {
                     name: 'mapSer',
                     type: 'map',
                     map: 'china',
                     roam: true,
                     geoIndex: 0,
                    itemStyle: { // 图形样式
                        normal: {
                            borderWidth: .5, //区域边框宽度
                            borderColor: '#009fe8', //区域边框颜色
                            areaColor: "#ffefd5", //区域颜色
                        },
                        emphasis: { // 鼠标滑过地图高亮的相关设置
                            borderWidth: .5,
                            borderColor: '#4b0082',
                            areaColor: "#fff",
                        }
                    },
                    //geo改色
                label: { // 图形上的文本标签
                        normal: {
                            show: true, //省份名称
                            fontSize: 8,
                        },
                        emphasis: {
                            show: true,
                            fontSize: 8,
                        },
                    
                 },
                },
            {
                realtimeSort: true, //是否开启该系列的实时排序
                seriesLayoutBy: "column", //指定如何对应dataset中的数据
                type: "bar", //柱状图
                
                
                itemStyle: { //图形样式
                    color: function (param) { //柱条的颜色,param参数就是item对应的柱子

                        //console.log(countryColors[param.value]);
                        return countryColors[param.value[1]] || "#5470c6";
                       },
                },
                
                
                encode: { //定义维度的编码(映射)
                    x: 3, //把第一个维度(输入)映射到x轴
                    y: 1, //把第四个维度映射到y轴
                },
                label: { //图形上的文本标签
                    show: true,
                    precision: 1, //标签的精度,表示保留一位小数
                    position: "right", //标签的位置
                    valueAnimation: true, //是否开启标签的数字动画
                    fontFamily: "monospace", //字体
                },
            },
        ],
        animationDuration: 0, //初始动画时长
        animationDurationUpdate: updateFrequency, //数据更新动画的时长
        // animationEasing: "linear", //初始动画缓动效果,因为没有初始动画,所以不需要写
        animationEasingUpdate: "linear", //数据更新动画缓动效果
        //原生图形元素组件,用来在图表中绘制一些形状
        graphic: {
            elements: [
                {
                    type: "text", //图形种类
                    right: 850,
                    bottom: 80,
                    style: {
                        text: startDate, //初始文本内容
                        font: "bolder 40px monospace",
                        fill: "rgba(0,180,255,0.8)",
                    },
                    z: 100,
                },
            ],
        },
    };
    myChart.setOption(option);
    
    updateepic = function (){
    for (let i = startIndex; i < dates.length - 1; ++i) {
        var b=0;
        (function (i,b) {
            sts.push(
            //每隔updateFrequency更新一次数据,一开始立马更新一次
            setTimeout(function () {
                updateYear(dates[i + 1]);
            }, (i - startIndex) * updateFrequency))
        })(i,b);
        b++
    }
    }
        var sts=[];

    delay = function (){
        for (var i = 0; i < sts.length; i++) {
              clearTimeout(sts[i]);
            }
            return
    }
    function updateYear(date) {
        let source = arr1.filter(function (d) {
            return d[0] === date;
        });
        let daymap = [];
        for(let i=0;ilength;i++){
            let obj={
                name:source[i][1],
                value:source[i][3],
            }
            daymap.push(obj);
            }

        option.series[1].data = source; //更新系列中的数据
        option.series[0].data = daymap;
        option.graphic.elements[0].style.text = date; //更新图表右下角的年份
        myChart.setOption(option);
                }
            });





```

回答不易,求求您采纳点赞哦

实现此目的的一种方法是使用 JavaScript 的setTimeout()函数以及一些变量来跟踪图表的状态。以下是如何实现开始和暂停按钮的示例:

  • 创建一个变量isRunning并将其设置为true页面加载时的值。
  • 在setTimeout()更新图表数据的函数中,添加对 的值的检查isRunning。如果isRunning是true,则更新图表数据并设置下次更新的超时时间。如果isRunning是false,则不要更新图表数据或设置新的超时时间。
  • 创建一个设置 to 的值的开始按钮isRunning和一个设置to的值true的暂停按钮。isRunningfalse
  • 在开始按钮的回调函数中,清除已有超时,setTimeout()再次调用函数更新图表数据。
    这是它在代码中的外观示例:
var isRunning = true;

function updateChartData() {
    if (isRunning) {
        // update chart data here
        setTimeout(updateChartData, 1000);
    }
}

function start() {
    isRunning = true;
    clearTimeout(timeoutId); // if you have set a timeoutId var
    updateChartData();
}

function pause() {
    isRunning = false;
}

updateChartData();

您还可以创建一个全局变量来存储 timeoutId 并使用它来清除启动函数调用的超时,以便它可以重新启动。

也可以使用setInterval()instead ofsetTimeout()定期更新图表数据。在这种情况下,您可以使用clearInterval()在单击暂停按钮时停止更新。