Learn the countdown effect of JavaScript core DOM and BOM operation with Mr. Pink

countdown effect

case analysis

① This countdown is constantly changing, so a timer is needed to change automatically (setInterval) Note: Int's I is an uppercase i! val's l is a lowercase L. Let me be long-winded.
② The hours, minutes and seconds are stored in the three black boxes.
③ The three black boxes use innerHTML to put the calculated hours, minutes, and seconds.
④ The first execution is also an interval of milliseconds, so the page will be blank just after refreshing.
⑤ It is best to adopt the method of encapsulating the function, so that the function can be called once first to prevent the blank problem when refreshing the page at the beginning.
⑥ When the countdown is over, it will prompt the past information.
⑦ Optimize, clear timerclearInterval().
Realize the effect diagram:
insert image description here

Code

basic structure

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>12-倒计时效果</title>
    <style>
      div {
      
      
        margin: 200px;
      }
      div>span {
      
      
        display: inline-block;
        width: 40px;
        height: 40px;
        background-color: #333;
        font-size: 20px;
        color: #fff;
        text-align: center;
        line-height: 40px;
      }
      /* 倒计时已过小提示 先是隐藏的 */
      .tisp {
      
      
        display: none;
        position: absolute;
        top: 65px;
        left: 25%;
        width: 300px;
        color: red;
        background-color: skyblue;
        line-height: 40px;
        text-align: center;
        font-size: 14px;
      }
    </style>
  </head>
  <body>
    <div>
      <span class="hour">14</span>
      <span class="minute">59</span>
      <span class="second">14</span>
    </div>
    <span class="tisp">已过倒计时时间,下次尽早~</span>
  </body>
</html>

insert image description here

new Date()

Date object
The Date object is used to work with dates and times.
Create a Date object: new Date()
For details, please browse: Date - Javascript | MDN
Because I am fed up with JavaScript code snippets, this time I use the learned load to do it under the body

Code:

// 以下的js语句将都会被放入到function(){}内
// 也就是function(){这里面!}
window.addEventListener('load', function(){
    
    } )


I use the parseInt() function that encapsulates a countdown to get an integer
. For the sake of overall beauty, I specially use a ternary expression to add 0 to the number below 10. Example
: h = h < 10 ? '0' + h : h

Code:

window.addEventListener('load', function(){
    
    
// 
    var hour = document.querySelector('.hour')      // 时
    var minute = document.querySelector('.minute')  // 分
    var second = document.querySelector('.second')  // 秒
    // 设定目标时间格式:'YYYY-MM-DD HH:mm:ss'
    var inputDate = +new Date('2022-09-23 16:54:00')
    // 封装一个倒计时函数
    function countDown(){
    
    
    // 获取调用的时间戳
      var nowData = +new Date()
      // 目标时间 - 当前时间 / 1000 得到 剩余秒数
      times = (inputDate - nowData)/1000 
      // 转化成时钟
      var h = parseInt(times/60/60%24)
      // 为了整体美观给10以下的数字补0
      h = h < 10 ? '0' + h : h
      hour.innerHTML = h
      // 转化成分钟
      var m = parseInt(times/60%60)
      m = m < 10 ? '0' + m : m
      minute.innerHTML = m
      // 转化成秒钟
      var s = parseInt(times % 60)
      s = s < 10 ? '0' + s : s 
      second.innerHTML = s
        }
      })

At this point, we are halfway done, but it is only executed once when running, so we need to use a timer.

Timer - setInterval()

There are two timer methods in the window, and the window can be omitted when calling. The delay time unit is milliseconds 1000 milliseconds = 1 second, which can be omitted, and the default is 0 if omitted.
setTimeout(execute function, delay time)
If you only want to execute it once, you can choose setTimeout
setInterval(execution function, delay time)
If you want to call the function continuously, you can choose setInterval.
We need to call the countdown function continuously, so we choosesetIntervalTo achieve the countdown effect

Code:

// 开启定时器
// 给定时器加标识符(名字)方便后续调用
var timer = setInterval(countDown,1000)

insert image description hereThe set target time is 2022-09-23 17:50:00 According to the current time, there is still one or two minutes left. We achieved it! However, careful friends have found that there will be a short pause when we start running or refreshing the countdown effect

Example image of the problem:

insert image description here
This problem is because our first execution is also an interval of milliseconds, so the page will be blank just after refreshing. The solution is to call the countdown function once before starting the timer.

// 加载页面时就调用一次防止有空白
countDown()

Countdown has expired

We shouldn't just implement the countdown effect, in order to give users a better experience, we can add another prompt.

Sample code:

// times是剩余的秒数
// 如果秒数小于0 即为已过倒计时时间,则隐藏时间,显示提示语
// 需要先去获取时间的div元素和提示的div元素
// 此代码片放置在倒计时函数countDown()的最后
if (times < 0) {
    
    
  div.style.display = 'none'
  tisp.style.display = 'block'
  // 此处还有一句
  } else {
    
    
  div.style.display = 'block'
  tisp.style.display = 'none'
}

Example renderings:
insert image description here

Optimize clear timer - clearInterval()

We mentioned earlier that the setInterval() timer will be called continuously. Do we think it will rest when the time is up? No, it's still calling.
Pictured above!
insert image description hereEven though the time has elapsed, the timer is still calling, these times we need to clear the timer.clearInterval()
The name we added to the timer earlier is also useful here.

Sample code:

// 此js代码片放置在判断剩余秒数是小于0内
clearInterval(timer)

Code example diagram:
insert image description here
Look at the diagram, our clear timer is successful. The timer is no longer called when the countdown has elapsed.

full code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>12-倒计时效果</title>
    <style>
      div {
      
      
        margin: 200px;
        position: absolute;
        top: 65px;
        left: 25%;
      }
      div>span {
      
      
        display: inline-block;
        width: 40px;
        height: 40px;
        background-color: #333;
        font-size: 20px;
        color: #fff;
        text-align: center;
        line-height: 40px;
      }
      .tisp {
      
      
        display: none;
        position: absolute;
        top: 65px;
        left: 25%;
        width: 300px;
        color: red;
        background-color: skyblue;
        line-height: 40px;
        text-align: center;
        font-size: 14px;
      }
    </style>
    <script>
      window.addEventListener('load', function(){
      
      
        var hour = document.querySelector('.hour')      // 时
        var minute = document.querySelector('.minute')  // 分
        var second = document.querySelector('.second')  // 秒
        var div = document.querySelector('div')
        var tisp = document.querySelector('.tisp')
        // 你记得修改这个时间哟 
        var inputDate = +new Date('2022-09-23 18:31:00')
        // 加载页面时就调用一次防止有空白
        countDown()
        // 开启定时器
        var timer = setInterval(countDown,1000)
        // 封装一个倒计时函数
        function countDown(){
      
      
          var nowData = +new Date()
          times = (inputDate - nowData)/1000 
          var h = parseInt(times/60/60%24)
          h = h < 10 ? '0' + h : h
          hour.innerHTML = h

          var m = parseInt(times/60%60)
          m = m < 10 ? '0' + m : m
          minute.innerHTML = m

          var s = parseInt(times % 60)
          s = s < 10 ? '0' + s : s 
          second.innerHTML = s
          if (times < 0) {
      
      
            div.style.display = 'none'
            tisp.style.display = 'block'
            clearInterval(timer)
          } else {
      
      
            div.style.display = 'block'
            tisp.style.display = 'none'
          }
        }
      })
    </script>
  </head>
  <body>
    <div>
      <span class="hour">14</span>
      <span class="minute">59</span>
      <span class="second">14</span>
    </div>
    <span class="tisp">已过倒计时时间,下次尽早~</span>
  </body>
</html>

Guess you like

Origin blog.csdn.net/weixin_46278178/article/details/127014032