1、原因
【需求】我封装了一个格式化时间的工具函数,想在调用时将他放在定时任务里,每秒打印一次当前时间
【问题】我实现之后发现每次调用只能获取固定的时间,也就是第一次获取的时间,之后每次打印都是第一次获取的时间,没有变化
//
let dateTools = {
getLocalTime:getLocalTime(),
getLocalTime_Template:getLocalTime_Template()
}
// 获取当前时间(时分秒)
function getLocalTime(){
const date = new Date()
const time = {
hour:date.getHours(),
minutes:date.getMinutes(),
second:date.getSeconds()
}
return time;
}
// 获取当前时间(时分秒)模板后的
function getLocalTime_Template(){
const date = new Date()
const time = {
hour:date.getHours(),
minutes:date.getMinutes(),
second:date.getSeconds()
}
return `${time.hour.toString().padStart(2, '0')}:${time.minutes.toString().padStart(2, '0')}:${time.second.toString().padStart(2, '0')}`;
}
export default dateTools;
import time from "@/utils/FromatDate"
export default {
methods:{
gettime(){
//每秒打印下当前时间
setInterval(() => {
console.log(time.getLocalTime_Template());
}, 1000);
}
},
}
输出结果
12:17:10
12:17:10
12:17:10
12:17:10
12:17:10
12:17:10
......
都是打印第一次获取到的时间值
2、如何解决
询问ai过后,发现一个容易忽略的知识点
let dateTools = {
getLocalTime:getLocalTime(),
getLocalTime_Template:getLocalTime_Template()
}
//我工具函数中的这个dateTools对象中getLocalTime_Template:getLocalTime_Template()后面函数加了()
//加了()表示你调用了这个函数,所以,获取到dateTools对象时,他就将第一次获取到的值付给了getLocalTime_Template
//第二次调用时,getLocalTime_Template的值自然就变成了第一次的值,以后每一次都是
函数():表示调用
函数:表示获取此函数,但未调用
懂了上面这个知识点,我们就可以正常解决问题了
let dateTools = {
getLocalTime:getLocalTime(),
getLocalTime_Template:getLocalTime_Template()
}
//我们只需要将getLocalTime_Template()的括号去掉,旨在每次都获取函数,但不调用
let dateTools = {
getLocalTime:getLocalTime,
getLocalTime_Template:getLocalTime_Template
}
//然后调用时将()加上,这样就实现了每次在使用时都去调用获取了当前时间,我们改下代码
import time from "@/utils/FromatDate"
export default {
methods:{
gettime(){
this.timer = setInterval(() => {
//time.getLocalTime_Template():这里调用时就加了()
console.log(time.getLocalTime_Template());
}, 1000);
}
},
//组件销毁时清除定时器函数操作
beforeDestroy() {
// 组件销毁时清除定时器,避免内存泄漏
clearInterval(this.timer);
}
}