在前端開發中,每每會遇到頁面須要實時刷新數據的狀況,給用戶最新的數據展現。前端
若是須要數據實時更新,咱們天然是須要使用定時器,不斷的調用接口數據,會相對的消耗內存。vue
data(){ return { intervalId:null } }, methods:{ // 定時刷新數據函數 dataRefreh() { // 計時器正在進行中,退出函數 if (this.intervalId != null) { return; } // 計時器爲空,操做 this.intervalId = setInterval(() => { console.log("刷新" + new Date()); this.initData(); //加載數據函數 }, 5000); }, // 中止定時器 clear() { clearInterval(this.intervalId); //清除計時器 this.intervalId = null; //設置爲null }, }, created(){ this.dataRefreh(); }, destroyed(){ // 在頁面銷燬後,清除計時器 this.clear(); }
本文轉自:https://blog.csdn.net/qq_41115965/article/details/102722540函數