通过ajax获取苏宁时间接口,秒值本地自动加1,setInterval计时器延迟解决,显示在页面上
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>闹表</title>
<script src="./js/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function() {
var $settime = document.getElementById('settime');
var now = new Date();
// 获取星期几
var week = getdate(now);
// 实现从苏宁接口只获取一次时间后,本地直接1秒递增方式来显示时间
// 时间格式必须是:"2020-08-18 10:09:08"
function dateAdd(d,num){
var d = new Date(
d.substring(0,4),
d.substring(5,7)-1,
d.substring(8,10),
d.substring(11,13),
d.substring(14,16),
d.substring(17,19));
d.setTime(d.getTime()+num*1000);
var month = d.getMonth()+1;
var date = d.getDate();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
var time_result = " "+todou(hour)
+":"+todou(minute)
+":"+todou(second)+ " " + toweek(week[0]);
// 写入title标签
document.title =
todou(month)
+"/"+todou(date)
+ time_result;
// 显示在页面
$settime.innerHTML = d.getFullYear()+"年"
+todou(month)
+"月"+todou(date)+"日"
+time_result;
}
// 小于10的数字补位
function todou(ev) {
if (ev < 10) {
ev = '0' + ev;
}
return ev.toString();
}
function getTime() {
var userurl = 'https://quan.suning.com/getSysTime.do';
$.ajax({
type: 'get',
url: userurl,
dataType: 'json',
success: function (data) {
// $settime.innerHTML = data.sysTime2.replace(/(\d{4}).(\d{1,2}).(\d{1,2})/g, '$1年$2月$3日') + " " + toweek(week[0]);
// 解决延迟方法
var startTime = new Date().getTime();
// console.log(startTime);
var count = 0;
function fixed() {
count++;
var offset = new Date().getTime() - (startTime + count * 1000);
var nextTime = 1000 - offset;
if (nextTime < 0) nextTime = 0;
setTimeout(fixed, nextTime);
dateAdd(data.sysTime2,count);
// console.log(new Date().getTime() - (startTime + count * 1000));
}
setTimeout(fixed, 1000);
// 以下方法有延迟
// var i = 0;
// updateNum();
// setInterval(updateNum, 1000);
// function updateNum()
// {
// dateAdd(data.sysTime2,++i);
// }
}
});
}
getTime();
// beginbTn.onclick = function () {
// nowtime();
// var timer = setInterval(nowtime, 1000);
// bTn.onclick = function () {
// clearInterval(timer);
// };
// };
function getdate(ev) {
var week = ev.getDay(); //星期(值0-6)
return [week];
}
function toweek(num) {
switch (num) {
case 0:
return '星期天';
case 1:
return '星期一';
case 2:
return '星期二';
case 3:
return '星期三';
case 4:
return '星期四';
case 5:
return '星期五';
case 6:
return '星期六';
}
}
});
</script>
</head>
<body>
<div id="settime" class="set_time"></div>
</body>
</html>