#独家
如何在拿到接口给出的设备时间戳后展示成本地时间并实时更新?

2023-06-08 0 1,665

目前有个需求是拿到设备传来的时间戳之后展示并实时更新设备时间,目前我的解决方案是这样的

onMounted(async () => {
  await getDeviceList()
  deviceList.forEach((item: any, index: number) => {
    timers[index] = setInterval(() => {
      item.localTime = new Date(
        new Date(item.localTime).getTime() + 1000
      ).toLocaleString()
    }, 1000)
  })
})

const getDeviceList = () => {
  deviceApi
    .getDeviceList()
    .then((res) => {
      const { data } = res
      deviceList = data.map((item: any) => {
        item.localTime = new Date(item.localTime).toLocaleString()
      })
    })
    .catch((err) => {})
}

不过这种方案设备时间会有大概2s的延迟,大佬们有好的解决方案把延迟降低到毫秒、微秒的级别吗?或者提供个思路也可以,前端小菜鸟拜谢!

const getDeviceList = () => {
  deviceApi
    .getDeviceList()
    .then((res) => {
      const { data } = res
      deviceList = data.map((item: any) => {
        const currentTime = Date.now()
        const devTime = Date.parse(item.localTime);
        // 在这里保存当前浏览器时间和设备时间的时间戳差值
        item.localTime = currentTime - devTime
      })
    })
    .catch((err) => {})
}

展示的时候只需要Date.now()减时间戳差值

目前有了一个解决方案,但不知道是不是最优解,果然还是菜鸡。代码如下

onMounted(async () => {
  await getDeviceList()
})

const getDeviceList = async () => {
  await deviceApi
    .getDeviceList()
    .then((res) => {
      const { data } = res
      deviceList = data.map((item: any) => {
        rest.localTime = new Date(rest.localTime).toLocaleString()
      })
      updateDeviceTime(deviceList)
    })
    .catch((err) => {})
}

const updateDeviceTime = (list: any) => {
  list.forEach((item: any, index: number) => {
    timers[index] = setInterval(() => {
      item.localTime = new Date(
        new Date(item.localTime).getTime() + 1000
      ).toLocaleString()
    }, 1000)
  })
}
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

1. JK下载官网所有资源来源于开发团队,加入会员即可下载使用!如有问题请联系右下角在线客服!
2. JK下载官方保障所有软件都通过人工亲测,为每位会员用户提供安全可靠的应用软件、游戏资源下载及程序开发服务。
3. JK开发团队针对会员诉求,历经多年拥有现今开发成果, 每款应用程序上线前都经过人工测试无误后提供安装使用,只为会员提供安全原创的应用。
4. PC/移动端应用下载后如遇安装使用问题请联系右下角在线客服或提交工单,一对一指导解决疑难。

JK软件下载官网 技术分享 如何在拿到接口给出的设备时间戳后展示成本地时间并实时更新? https://www.jkxiazai.com/1790.html

JK软件应用商店是经过官方安全认证,保障正版软件平台

相关资源

官方客服团队

为您解决烦忧 - 24小时在线 专业服务