//获取服务器时间
serverTime();
function serverTime() {
AjaxPost("commond/server_time.php", {}, function (result) {
if (result.code == "200") {
$(".times").html(result.datas['times']);
//将获取到的服务器时间传入定时器
beginaddtime(result.datas['times']);
} else {
layer.msg(result.datas)
}
});
}
function beginaddtime(datetime){
var nowdate=datetime;
//将定时器赋给全局变量
device_time = setInterval(function(){
nowdate=startTime(nowdate);
},1000)
}
function startTime(nowdate){
var today = new Date(nowdate);
//转换成时间戳加秒数
var addtimes = new Date(today.getTime() + 1000 );
var h = addtimes.getHours();
var m = addtimes.getMinutes();
var s = addtimes.getSeconds();
var y = addtimes.getFullYear();
var mo= addtimes.getMonth()+1;
var d= addtimes.getDate();
m = checkTime(m);
s = checkTime(s);
var nowdate=y+"-"+mo+"-"+d+" "+h+":"+m+":"+s;
$(".times").html(nowdate);
return nowdate;
}
function checkTime(i){
if(i<10){
i = "0"+i;
}
return i
}
//js存在一个问题,当切出当前页面时,时间会滞留
//监听页面,当切回当前页面时 重新获取时间
document.addEventListener("visibilitychange", function () {
if (!document.hidden) {
// 当切回页面 重启获取时间 启动定时器
serverTime();
}else{
// 不处于当前页面时 关闭这个定时器
clearInterval(device_time);
}
});
js 定时器
最新推荐文章于 2022-10-15 17:34:09 发布