我正在从服务器发送时间戳,我希望浏览器知道确切的时间。
我正在使用Moment,但觉得有几种方法可以达到这个目的。
我已经考虑在isSame()
中使用setInterval()
,但它似乎无法正常工作。
var interval = setInterval(function(){
if(moment().isSame(moment(data.server_time_stamp))){
console.log('MATCHES!!!')
clearInterval(interval)
}
}, 1)
其中data.server_time_stamp
是从服务器传递的时刻对象(计算为当前时间+10秒)。我已将其设置为utc()
,以便标准化服务器和客户端上的时区。
我还尝试将其设置为unix()
并在我的setInterval()
循环中,使用===
运算符来查看它们是否相同。像这样:
var interval = setInterval(function(){
if(cur_time === data.screenshot_time){
console.log('MATCHES!!!')
clearInterval(interval)
}
}, 1)
尽管使用这种方法,它似乎不够精确。
最简单的方法是什么?
答案 0 :(得分:1)
你应该像@some所说的那样比较秒而不是毫秒。 它可以这样工作:
moment.utc().isSame(moment(data.server_time_stamp), 'second');
答案 1 :(得分:0)
我最终使用的方法(但尚未彻底测试)是使用timesync来同步所有时钟,然后在setInterval()中匹配当前时间
var ts = timesync.create({
server: SERVER + '/timesync'
});
var interval = setInterval(function(){
if(moment(ts.now()).utc().unix() === data.screenshot_time){
console.log('SNAPPED!!!')
take_photo()
clearInterval(interval)
}
}, 1)