前端js实现一个时间实时更新效果
按秒刷新,实现效果如图:
简单原理就是:
封装一个时间格式的方法,加一个定时器,每秒去刷新一次,模拟成为时间更新效果
1. 封装公共方法
export function timeNow() {
let vWeek, vWeek_s, year, month, day, hours, minutes, seconds;
vWeek = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
let date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hours = date.getHours();
hours = hours > 9 ? hours : "0" + hours;
minutes = date.getMinutes();
minutes = minutes > 9 ? minutes : "0" + minutes;
seconds = date.getSeconds();
seconds = seconds > 9 ? seconds : "0" + seconds;
vWeek_s = date.getDay();
let time = year + "年" + month + "月" + day + "日" + "\t" + hours + ":" + minutes + ":" + seconds + "\t" + vWeek[vWeek_s];
return time
}
可以根据需求更改展现格式
2. 使用
引入:
import { timeNow } from "../../utils/getMaininfo";
从页面加载起,开始执行:
getAll() {
this.tiemEq = setInterval(() => {
/* 时间 */
this.nowTime = timeNow();
}, 1000);
}
注:这里给定时器生成定义,以便后续销毁
3. 销毁
由于定时器的特殊性,在关闭页面时,及时销毁,避免造成资源浪费甚至内存溢出
// vue生命周期
beforeDestroy() {
/* 关闭页面销毁所有定时器 */
clearInterval(this.tiemEq);
}