现在几点了?

本文解析了百度网页上显示当前时间的实现方式,采用创建script标签请求服务器时间,并通过定时更新客户端时间显示,确保时间准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   最近我同事发现在百度中输入现在几点了,第一条是“北京时间 - 国家授时中心标准时间” 。然后我同事就想它怎麽写的。于是我写就想看它到底是怎麽写的。因为我觉得它不会像我一样傻,用jsp写死在js里再时不时的用ajax访问后台“几点了啊?”。

 它是这样,在里面有一个执行匿名函数: 

 

 1  ( function (){
 2  var  week  =   ' 日一二三四五六 ' ;
 3  var  innerHtml  =   ' {0}:{1}:{2} ' ;
 4  var  dateHtml  =   " {0}月{1}日  周{2} " ;
 5  var  timer  =   0 ;
 6   
 7  function  format(str, json){
 8       return  str.replace( / {(\d)} / g,  function (a, key) {
 9           return  json[key];
10      });
11  }
12   
13  function  p(s) {
14       return  s  <   10   ?   ' 0 '   +  s : s;
15  }
16   
17  window.baidu_time  =   function (timeObj){    
18       var  time  =  timeObj.time;
19      initTime  =  time;
20       if (timer  !=   0 ){
21          clearInterval(timer);
22          timer  =   0 ;
23      }
24      show(time);
25      timer  =  setInterval( function (){
26          time  +=   1000 ;
27          show(time);
28      },  1000 );
29  }
30   
31  function  show(time){
32       var  now  =   new  Date(time);
33      document.getElementById( ' time ' ).innerHTML  =  format(innerHtml, [p(now.getHours()), p(now.getMinutes()), p(now.getSeconds())]);
34      setClockTime(time);
35      document.getElementById( ' date ' ).innerHTML  =  format(dateHtml, [ p((now.getMonth() + 1 )), p(now.getDate()), week.charAt(now.getDay())]);
36  }
37   
38  function  init(){
39       var  elm  =  document.createElement( ' SCRIPT ' );
40      elm.src  =   ' http://open.baidu.com/app?module=beijingtime&t= '   +   new  Date().getTime();
41      document.getElementsByTagName( ' HEAD ' )[ 0 ].appendChild(elm);
42      setTimeout( function (){init()},  60000 );
43  }
44   
45  init();
46   
47  })();

 

 

 

 然后执行init();,我觉得它有意思的地方是没有用ajax的方法去访问服务器获得时间,而是创建一个script标签来访问后台:

ExpandedBlockStart.gif 代码
var  elm  =  document.createElement( ' SCRIPT ' );
elm.src 
=   ' http://open.baidu.com/app?module=beijingtime&t= '   +   new  Date().getTime();
document.getElementsByTagName(
' HEAD ' )[ 0 ].appendChild(elm);
setTimeout(
function (){init()},  60000 );

 

 让我不明白的是src = 'http://open.baidu.com/app?module=beijingtime&t=' + new Date().getTime();为什麽还要有new Date().getTime()。获取一下你的计算机时间,然后和它的服务器对一下说:“哈哈,你没我准!”。有哪位大侠明白吗?

 

转载于:https://www.cnblogs.com/songxiaoyin/archive/2010/01/27/1657209.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值