定時刷新頁面或請求接口


1. 需求:

   由於數據計算量比較大,所以接口請求返回數據可能會比較慢,這時候咋整勒。為了提高用戶體驗,想到了前端定時刷新,定時器走起~

2. 定時請求接口

  a. 先定義個全局的定時器,取名timer

  b.

// 組件卸載時清空定時器 
componentWillUnmount() {
    clearInterval(this.timer)
  }


timedRefresh = () => {
    clearInterval(this.timer)
    if ( 我是條件 ) {
      this.timer = setInterval(() => {
        fetchSomething(params1, params2)  // 每隔3s請求一次接口
      }, 3000)
    } else {
      clearInterval(this.timer)    // 取消定時器
    }
  }

 

  

3. 定時刷新頁面

  a. 先定義個全局的定時器,取名timer

  b.

// 組件卸載時清空定時器 
componentWillUnmount() {
    clearInterval(this.timer)
  }


timedRefresh = () => {
    clearInterval(this.timer)
    if ( 我是條件 ) {
      this.timer = setInterval(() => {
        window.location.reload()    // 每隔3s刷新整個頁面
      }, 3000)
    } else {
      clearInterval(this.timer)    // 取消定時器
    }
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM