通过后台返回的时间戳,显示系统运行时期???-灵析社区

雁过留痕

let startTime = ref()// 起始时间 let timer = ref(null)// 计时器 let currentTime: any = ref('')// 当前时间 onMounted(() => { timer.value = setInterval(() => { APPRunning(); // 每隔一秒更新当前时间 }, 1000); }) onBeforeUnmount(() => { clearInterval(timer.value); // 组件卸载前清除定时器 }) // 系统运行时间 function APPRunning() { const id = window.localStorage.getItem('RowID'); api.RunningTime(id).then((RunningTimeData) => { const { data: res } = RunningTimeData; console.log('运行时间', res); const startTimeItem = res.data; // 更新系统时间的函数 currentTime.value = convertTimestampToTime(startTimeItem); // 转换为日、时、分、秒格式 // 第一次调用更新时间的函数 }); } function convertTimestampToTime(timestamp) { currentTime.value = new Date(); // 获取当前时间 const days = Math.floor(timestamp / (1000 * 60 * 60 * 24)); // 计算天数 const hours = Math.floor((timestamp % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); // 计算小时 const minutes = Math.floor((timestamp % (1000 * 60 * 60)) / (1000 * 60)); // 计算分钟 const seconds = Math.floor((timestamp % (1000 * 60)) / 1000); // 计算秒数 // 格式化处理 const formattedTime = days + '天 ' + hours + '小时 ' + minutes + '分钟 ' + seconds + '秒'; return formattedTime; } 此代码会一直调用APPRunning()函数接口,以此来达到持续的更新秒数,请问大佬们,我该怎样优化才可以使APPRunning()调用一次,其余时间都是只更新秒数不会重复调用接口。

阅读量:199

点赞量:13

问AI
let startTime = ref(null) let timer = ref(null) let currentTime: any = ref('') onMounted(() => { // 获取初始时间戳 getInitialTimestamp(); // 设置定时器,每秒更新当前时间 timer.value = setInterval(() => { updateCurrentTime(); }, 1000); }) onBeforeUnmount(() => { clearInterval(timer.value); // 组件卸载前清除定时器 }) // 获取初始时间戳 async function getInitialTimestamp() { const id = window.localStorage.getItem('RowID'); try { const RunningTimeData = await api.RunningTime(id); const { data: res } = RunningTimeData; console.log('运行时间', res); const startTimeItem = res.data; startTime.value = startTimeItem; // 保存初始时间戳 updateCurrentTime(); // 第一次调用更新时间的函数 } catch (error) { console.error('获取初始时间戳失败:', error); } } // 更新当前时间 function updateCurrentTime() { if (startTime.value !== null) { const timestamp = Date.now() - startTime.value; // 计算已经过去的时间 currentTime.value = convertTimestampToTime(timestamp); // 转换为日、时、分、秒格式 } } // 时间戳转换函数 function convertTimestampToTime(timestamp) { const days = Math.floor(timestamp / (1000 * 60 * 60 * 24)); // 计算天数 const hours = Math.floor((timestamp % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); // 计算小时 const minutes = Math.floor((timestamp % (1000 * 60 * 60)) / (1000 * 60)); // 计算分钟 const seconds = Math.floor((timestamp % (1000 * 60)) / 1000); // 计算秒数 // 格式化处理 const formattedTime = days + '天 ' + hours + '小时 ' + minutes + '分钟 ' + seconds + '秒'; return formattedTime; }