这里使用的Promise很简单,在Promise实例后面的then有两个参数,第一个参数是异步访问成功之后执行的函数,第二个参数是异步访问失败之后执行的函数.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>基于服务器事件的倒计时</title>
<style>
.timeBox{
margin: 20px auto;
width: 300px;
height: 50px;
line-height: 50px;
text-align: center;
border: 1px dashed lightblue;
font-size: 12px;
}
.timeBox span {
color: lightcoral;
font-weight: bolder;
}
</style>
</head>
<body>
<div class="timeBox">
距离抢购还剩
<span>-- : -- : --</span>
</div>
<script type="text/javascript">
let _serverTime = null;
let timeBox = document.querySelector('.timeBox')
let timeSpan = timeBox.querySelector('span');
let autoTime = null;
//获取时间
let getServerTime = function getServerTime(){
if (_serverTime) {
_serverTime = new Date(_serverTime.getTime() + 1000);
return _serverTime;
}
return new Promise(resolve => {
let xhr = new XMLHttpRequest(),
serverTime = null;
xhr.open('HEAD', 'count_down.html');
xhr.onreadystatechange = () => {
if (xhr.readyState === 2) {
serverTime = new Date(xhr.getResponseHeader('date'));
_serverTime = serverTime;
resolve(serverTime);
}
}
xhr.send(null);
});
};
//计算倒计时
let computedTime = function computedTime (){
let promise = getServerTime();
promise instanceof Promise ? promise.then(f()) : f(promise);
function f(serverTime) {
let nowTime = serverTime,
tarTime = new Date('2019/02/24 20:00:00'),
diffTime = tarTime - nowTime;
if (diffTime >= 0) {
let hours = Math.floor(diffTime / (1000 * 60 * 60));
diffTime = diffTime - hours * (1000 * 60 * 60);
let minutes = Math.floor(diffTime / (1000 * 60));
diffTime = diffTime - minutes * (1000 * 60);
let seconed = Math.floor(diffTime / 1000);
hours < 10 ? hours = '0' + hours : null;
minutes < 10 ? minutes = '0' + minutes : null;
seconed < 10 ? seconed = '0' + seconed : null;
timeSpan.innerHTML = `${hours} : ${minutes} : ${seconed}`;
return;
}
timeSpan.innerHTML = '-- : -- : --';
clearInterval(autoTime);
}
};
computedTime();
autoTime = setInterval(computedTime, 1000);
</script>
</body>
</html>