不刷新页面的情况下,开启关闭定时器+ 在切换页面时开启关闭计时器

一、在切换页面时关闭/启动计时器

  const timer = setInterval(() => {
      // 切换页面关计时器
      if (document.getElementById("main") === null) {
        window.clearInterval(timer);
        return;
      }
      this.getProgress(batchNo, codes)
    }, 1000);

二、不刷新页面的情况下,自如的开启关闭定时器

左侧树选择后,进度条progressNum要重置0

进度条值为100%时

按钮代码:

场景逻辑:

1、左侧树选区划,点按钮,然后调用获取批次号的接口

注意:每次选区划的时候进度条progressNum要重置0

2、以区划代码和批次号为入参,调用获取进度条值的接口,进度条值的接口每秒刷新1次

注意:在progressNum为100时,要停止每秒调接口

代码:

 /** 获取五码编写批次号 */
  getBatchNo = async () => {
    const { regionCodes, progressNum } = this.state;
    if (regionCodes && regionCodes.length > 0) {
      const result = await                     
            DatabaseManageProvider.getCompile(regionCodes.toString())
      this.setState({
        batchNo: result,
      }, async () => {
// !!!开启计时器,并1S刷新获取进度值progressNum的接口
          this.timerStart(result, regionCodes);
      })
    }
  };
 /** 获取进度*/
  getProgress = async (batchNo: string, codes: string[]) => {
// 调用获取进度条值progressNum接口之前,先判断进度值progressNum如果100,则调用关闭计时器的方法
    if (this.state.progressNum === 100) {
      this.timerEnd();
    }
    if (codes && codes.length > 0) {
      const params = {
        regionCodes: codes.toString(),
        batchNo,
      }
      const num = await DatabaseManageProvider.getProgress({ ...params });
      this.setState({
        progressNum: +num,
      });
    }
  };

!!!!最重要的开启和关闭计时器的方法

 timerList是长度为1的数组

 state: State = {
    batchNo: "",
    progressNum: 0,
    slTableNames: [],
    sxTableNames: [],
    open: false,
  };
  
  timerList: number[] = [];
  timer = 0; 

/** 计时器open*/
  timerStart = (batchNo: string, codes: string[]) => {
    const timer = setInterval(() => { this.getProgress(batchNo, codes) }, 1000);
    // 计时器调用一侧会有一个ID,需要记录存在全局timerList里,timerList是一个长度为1的数组,比如:[27]
    this.timerList.push(timer)
  }
  /** 计时器close */
  timerEnd = () => {
    // console.log("关闭");
    // 挨个遍历timerList,挨个关闭
    console.log(this.timerList, "this.timerList--->");//[24]
    this.timerList.forEach((item, index) => { 
      clearInterval(item);
    })
    this.timerList = []
    this.timer = 0;
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值