在前端开发中,每每会遇到页面须要实时刷新数据的状况,给用户最新的数据展现。前端
若是须要数据实时更新,咱们天然是须要使用定时器,不断的调用接口数据,会相对的消耗内存。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函数