这里使用的Promise很简单,在Promise实例后面的then有两个参数,第一个参数是异步访问成功之后执行的函数,第二个参数是异步访问失败之后执行的函数.

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>基于服务器事件的倒计时</title>
    6. <style>
    7. .timeBox{
    8. margin: 20px auto;
    9. width: 300px;
    10. height: 50px;
    11. line-height: 50px;
    12. text-align: center;
    13. border: 1px dashed lightblue;
    14. font-size: 12px;
    15. }
    16. .timeBox span {
    17. color: lightcoral;
    18. font-weight: bolder;
    19. }
    20. </style>
    21. </head>
    22. <body>
    23. <div class="timeBox">
    24. 距离抢购还剩
    25. <span>-- : -- : --</span>
    26. </div>
    27. <script type="text/javascript">
    28. let _serverTime = null;
    29. let timeBox = document.querySelector('.timeBox')
    30. let timeSpan = timeBox.querySelector('span');
    31. let autoTime = null;
    32. //获取时间
    33. let getServerTime = function getServerTime(){
    34. if (_serverTime) {
    35. _serverTime = new Date(_serverTime.getTime() + 1000);
    36. return _serverTime;
    37. }
    38. return new Promise(resolve => {
    39. let xhr = new XMLHttpRequest(),
    40. serverTime = null;
    41. xhr.open('HEAD', 'count_down.html');
    42. xhr.onreadystatechange = () => {
    43. if (xhr.readyState === 2) {
    44. serverTime = new Date(xhr.getResponseHeader('date'));
    45. _serverTime = serverTime;
    46. resolve(serverTime);
    47. }
    48. }
    49. xhr.send(null);
    50. });
    51. };
    52. //计算倒计时
    53. let computedTime = function computedTime (){
    54. let promise = getServerTime();
    55. promise instanceof Promise ? promise.then(f()) : f(promise);
    56. function f(serverTime) {
    57. let nowTime = serverTime,
    58. tarTime = new Date('2019/02/24 20:00:00'),
    59. diffTime = tarTime - nowTime;
    60. if (diffTime >= 0) {
    61. let hours = Math.floor(diffTime / (1000 * 60 * 60));
    62. diffTime = diffTime - hours * (1000 * 60 * 60);
    63. let minutes = Math.floor(diffTime / (1000 * 60));
    64. diffTime = diffTime - minutes * (1000 * 60);
    65. let seconed = Math.floor(diffTime / 1000);
    66. hours < 10 ? hours = '0' + hours : null;
    67. minutes < 10 ? minutes = '0' + minutes : null;
    68. seconed < 10 ? seconed = '0' + seconed : null;
    69. timeSpan.innerHTML = `${hours} : ${minutes} : ${seconed}`;
    70. return;
    71. }
    72. timeSpan.innerHTML = '-- : -- : --';
    73. clearInterval(autoTime);
    74. }
    75. };
    76. computedTime();
    77. autoTime = setInterval(computedTime, 1000);
    78. </script>
    79. </body>
    80. </html>