javascript - js获取服务器时间,但用了setInterVal后,就回到1970-1-1
ringa_lee
ringa_lee 2017-04-11 12:34:34
[JavaScript讨论组]
var op = document.createElement('p'); 
op.id = 'p1'; 
document.body.appendChild(op);
document.getElementById('p1').style.position="fixed";
document.getElementById('p1').style.left="0";
document.getElementById('p1').style.top="180px";
document.getElementById('p1').style['z-index']="200";
document.getElementById('p1').style.background="#38f";
document.getElementById('p1').style.color="#fff";


var time,nt,add1s;

ajax();
function ajax(){
      var xhr = null;
            if(window.XMLHttpRequest){
            xhr = new window.XMLHttpRequest();
            }else{ // ie
            xhr = new ActiveObject("Microsoft")
            }
      // 通过get的方式请求当前文件
      xhr.open("get","/");
      xhr.send(null);
      // 监听请求状态变化
            xhr.onreadystatechange = function(){
                  time = null,
                  curDate = null;
                if(xhr.readyState===2){
                      // 获取响应头里的时间戳
                      time = xhr.getResponseHeader("Date");
                      aa(time)//第一次执行的时候正常
setInterval("aa(time)",1000)//执行setInterval,就变成1970-1-1 8:00:00


                }
                
            }
}

function aa(time){
add1s=new Date(time).getTime()+1000;
nt=new Date();
nt.setTime(add1s);//设置新时间比旧时间多一秒
time=nt.setTime(add1s);//把新设置的时间赋给变量time,目的是在下次调用时,在多一秒的基础上继续加1秒
 document.getElementById('p1').innerHTML="服务器时间:"+nt.getFullYear()+"-"+(nt.getMonth()+1)+"-"+nt.getDate()+" "+nt.getHours()+":"+nt.getMinutes()+":"+nt.getSeconds();
 console.log("时间"+new Date(time))
}

执行setInterval("aa(time)",1000)的时候就不正常了,是为什么呢?

ringa_lee
ringa_lee

ringa_lee

全部回复(2)
巴扎黑

setInterval("aa(time)",1000)
改成

setInterval(function () {
  aa(time)
},1000)
高洛峰
time=null

去掉,或者移到 onreadystatechange 外


教你如何查错

  • 从第一次正常的现象可知: aa 没错。但后续都错了,只能说明: aa 的环境出了问题,在此为参数 time

  • 搜索所有有可能更改全局 time 的地方,你会发现: 当 readystate 不为 2时,time 会被置 null

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号