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

 

问题描述:

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

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的延迟,大佬们有好的解决方案把延迟降低到毫秒、微秒的级别吗?或者提供个思路也可以,前端小菜鸟拜谢!


 

第 1 个答案:

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

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)
  })
}

 

第 2 个答案:

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()减时间戳差值


目前了解到的有 Naive UI、varlet、tailwind UI、daisy UI,主要考虑的有两点:支持nuxt3,兼容p ...