【发布时间】:2019-11-05 16:31:26
【问题描述】:
我创建了一个 websocket (wss) 客户端来监听来自套接字服务器的消息。消息从登录控制台客户端的服务器连续发送。我想测量这些消息之间的时间(我知道它们每 5 秒发生一次,但我需要计算时间,因为不能保证 5 秒)。
我曾考虑通过 Date.now() 存储上一条消息的时间,然后查找最新消息的时间来计算时差,但我不确定如何做到这一点。
socket.onmessage = (event) => {
if (event.data.substr(4, 9) === 'heartbeat') {
console.log(event.data.substr(2)) // logs msg to console
timeHeartbeats(event.data.substr(2), Date.now())
}
}
// I'm not actually keeping track of the time for 2 messages which is the issue
const timeHeartbeats = (json, mostRecent) => {
console.log(Date.now() - mostRecent) // 0 b/c Date.now() is the same as mostRecent (should be ~5000ms if time calc is correct)
}
【问题讨论】:
标签: javascript time websocket