Realization of Simple Countdown Effect in JavaScript

countdown effect

Realized by js built-in date object Date

Effectiveness analysis:

Core algorithm:

  1. The input time minus the current time is the remaining time, that is, the countdown.
  2. Do it with a timestamp. The total number of milliseconds of the user input time minus the total number of milliseconds of the current time is the number of milliseconds of the remaining time.
  3. Convert the total number of milliseconds of the remaining time to days, hours, minutes, and seconds (timestamps are converted to hours, minutes, and seconds)

The conversion formula is as follows:

  • d = parseInt(total seconds / 60 / 60 / 24); // Calculate the number of days
  • h = parseInt(total seconds / 60 / 60 % 24) // calculate hours
  • m = parseInt(total seconds / 60 % 60); // Calculate fraction
  • s = parseInt(total seconds% 60); // Calculate the current seconds

Specific code segment:

  function countDown(time) {
    
    
        //现在时间的总的毫秒数
        var nowTimes = +new Date();
        //用户输入时间总的毫秒数
        var inputTimes = +new Date(time);
        //剩余时间的毫秒数
        var times = (inputTimes - nowTimes) / 1000;
        //把剩余时间总的毫秒数转换为天、时、分、秒 (时间戳转换为时分秒)
        d = parseInt(times / 60 / 60 / 24); 
        d = d < 10 ? '0' + d : d;
        h = parseInt(times / 60 / 60 % 24) 
        h = h < 10 ? '0' + h : h;
        m = parseInt(times / 60 % 60); 
        m = m < 10 ? '0' + m : m;
        s = parseInt(times % 60);  
        s = s < 10 ? '0' + s : s;
        return d+'天'+h+'时'+m+'分'+s+'秒';
    }
     // 把函数的返回值(字符串形式)渲染到body标签内
     document.body.innerHTML = countDown('2021-03-19 22:00:00')
    // 定时器 每隔1秒渲染一次
    setInterval(function () {
    
    
        document.body.innerHTML = countDown('2021-03-19 22:00:00')
    }, 1000)

Realize the effect:
insert image description here

Note: In the core algorithm, it is not possible to directly subtract hours, minutes and seconds, such as subtracting 25 minutes from 05 minutes, and the result will be negative. The correct operation is to obtain the total number of milliseconds and subtract them to find the difference.

Welcome to read, hope to help you!

Guess you like

Origin blog.csdn.net/weixin_42146585/article/details/115016027