JavaScript NTP 时间 [英] JavaScript NTP time

查看:21
本文介绍了JavaScript NTP 时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个计数脚本,用于计算旧日期和今天之间的时间.
一切正常,直到我在错误日期的计算机上进行测试并看到结果.
所以我找到了一种通过 http://json-time.appspot.com/time 获取 NTP 时间的方法.json.
问题是我每毫秒都需要当前时间,因为我想计算毫秒数,但是不可能每毫秒向 NTP 服务器发送请求.
这是一些示例代码,用于查看我在写什么

I'm writing a counting script who counts the time between an old date and today.
Everything worked good until I tested on a computer with wrong date and saw the results.
So I found a way to get NTP time via http://json-time.appspot.com/time.json.
The problem is that I need the current time every millisecond because I want to count the milliseconds but Its impossible the send request to the NTP server every milisecond.
This is some example code to see what I'm writing about

            var today;
        $(document).ready(function(){

            $.data = function(success){
                $.get("http://json-time.appspot.com/time.json?callback=?", function(response){
                    success(new Date(response.datetime));
                }, "json");
            };
        });

        function update(){
            var start = new Date("March 25, 2011 17:00:00");
            //var today = new Date();
            $.data(function(time){
                today = time;
            });
            var bla = today.getTime() - start.getTime();
            $("#milliseconds").text(bla);
        }

        setInterval("update()", 1);

推荐答案

首先,JS 调度器有一定的粒度——也就是说,你可以请求一个小于 20 毫秒的间隔,但它不会触发立即 - 您可以看到每 20 毫秒触发 20 个事件.

First of all, the JS scheduler has a certain granularity - that is, you can request an interval smaller than, say, 20 msec, but it will not fire immediately - what you could see is 20 events fired off every 20 msec.

其次,即使可以,这也不是一个好主意:您将每秒从使用此脚本的每台计算机发出 1000 个请求.即使客户端及其连接可以处理这个问题,对于 JSON 服务器来说也无异于 DDoS.

Second, even if you could, this is not a good idea: you would be making 1000 requests every second, from every computer which uses this script. Even if the client and their connections could handle this, it's nothing short of a DDoS for the JSON server.

你可以这样做:

  • 从 JSON-NTP 获取时间(一次),这将是一个日期
  • 获取当地时间(一次),这将是一个日期
  • 计算 NTP 和本地时间之间的差异(一次),这可能是本地时间关闭的毫秒数
  • 每次计算时,都要考虑差异

这篇关于JavaScript NTP 时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆