PK creative Spring Festival, I am participating in the “Spring Festival creative submission contest”, please see the Spring Festival creative submission contest for details

Spring Festival Countdown

Hello everyone, MY name is Starqin, a front-end white. At the same time, I am also trying to learn javascritP. I have not been good at mathematics since junior high school, so I am not interested in things of calculation. For example, I cannot clearly remember how many days are left before the Spring Festival, so I wrote the small case I want to share today — The Countdown to the Spring Festival

The key of this small case is the use of timer and js date object use, set, conversion.

Js timer setInterval

SetInterval is a function that takes two arguments, the first a callback and the second a numeric parameter specifying how often, in milliseconds, the previous callback should be executed

setInterval(function(){
    console.log(1)},1000);
Copy the code

The above code means that printing 1 is performed every second

With this function we can make the program move by itself, and do it every second.

Js Date object Date

Js Date objects are instantiated using the built-in Date() constructor

Instantiate the date object (get the current time)

const nowDate = new Date(a);Copy the code

The instantiated object is also the current time. Since we need to do the countdown function, we need to calculate. Therefore, we can directly convert the obtained time into a timestamp, and then use the timestamp to calculate.

Date format to timestamp method

nowDate.getTime();
Copy the code

After we get the current time, we can’t directly get the date of the Spring Festival, because the program doesn’t know the date of the Spring Festival, so we need to tell the program the date of the Spring Festival in 2022

The date object sets the time

const endDate = new Date('2022/2/1 0:0:0');
Copy the code

Time difference calculation

After knowing the current time and the end time, we need to convert these two times into timestamps for easy calculation

let now = nowDate.getTime();
let end = endDate.getTime();
// Time difference = End time - current time
let cha = end - now;
Copy the code

Timestamp conversion

When we calculate, we will get a time difference, and this time difference is also a timestamp, so we need to go further and convert this result into days, hours, minutes and seconds

Since the js time is in milliseconds, we can divide the timestamp by 1000 to get a timestamp in seconds

cha = cha / 1000;
Copy the code

According to the time base system, one second =1s, one minute =60s, one hour =3600s, and one day =86400s. Therefore, we make conversion

// Convert the timestamp to days
var d =  cha / 86400;
// Convert the timestamp to the time
var h = cha % 86400 / 3600;
// Convert the timestamp to points
var ms = cha % 3600 / 60;
// Convert the time to seconds
var s  = cha % 60;
Copy the code

And just to make it easier for you to understand, the above transformation, you can remember it this way

Maximum unit = Total number/Maximum unit base This unit = Total number % Next unit base/this unit baseCopy the code

After calculating the time difference, we just need to put it into the timer callback function. This allows us to perform calculations every second and render the results to the page.

Optimization of this program

Since the timer is always executed, the time will always be calculated. After the Spring Festival, there may be a negative number because the time is still calculated, which is also a BUG. So we need to stop the program when the countdown is zero.

Stop the above procedure, in fact, is to clear the timer

Clear the timing premise

Timers are stored in a variable

const t = setInterval(function(){
    console.log(1)},1000);
Copy the code

Method of clearing timer

clearInterval(); Or clearTimeout ();

clearInterval(t);
/*clearTimeout(t); * /
Copy the code

Note: clearInterval() can be used for both timers and delayers; Or clearTimeout (); remove

All right, let’s go to the code

// Encapsulates the function that gets the element
function getEle(obj) {
    var list = [];
    list = document.querySelectorAll(obj);
    if (list.length > 1) {
        return list;
    } else if (list.length == 1) {
        return list[0];
    } else {
        console.warn('No capture'+ obj); }}// Get the page element
var d = getEle('#d');
var h = getEle('#h');
var m = getEle('#m');
var s = getEle('#s');


// Subtract two times
// Encapsulates a calculation function
function comTime(endTime) {
    var obj = new Object(a);var date = new Date(a);var setDate = new Date(endTime);
    var now = date.getTime();
    var end = setDate.getTime();
    if (now > end) {
        var remain = date - setDate;
        // Convert the remaining time to seconds
        var remain = remain / 1000;
        // Convert to days. A day equals 86400 seconds
        obj.D = parseInt(remain / 86400);
        obj.D = obj.D >= 10 ? obj.D : '0' + obj.D;
        // One hour of conversion equals 3600 seconds
        obj.H = parseInt(remain % 86400 / 3600);
        obj.H = obj.H >= 10 ? obj.H : '0' + obj.H;
        // Convert to one minute equals 60 seconds
        obj.M = parseInt(remain % 3600 / 60);
        obj.M = obj.M >= 10 ? obj.M : '0' + obj.M;
        / / to seconds
        obj.S = parseInt(remain % 60 / 1);
        obj.S = obj.S >= 10 ? obj.S : '0' + obj.S;
        return obj;
    } else if (now < end) {
        var remain = setDate - date;
        // Convert the remaining time to seconds
        var remain = remain / 1000;
        // Convert to days. A day equals 86400 seconds
        obj.D = parseInt(remain / 86400);
        obj.D = obj.D >= 10 ? obj.D : '0' + obj.D;
        // One hour of conversion equals 3600 seconds
        obj.H = parseInt(remain % 86400 / 3600);
        obj.H = obj.H >= 10 ? obj.H : '0' + obj.H;
        // Convert to one minute equals 60 seconds
        obj.M = parseInt(remain % 3600 / 60);
        obj.M = obj.M >= 10 ? obj.M : '0' + obj.M;
        / / to seconds
        obj.S = parseInt(remain % 60 / 1);
        obj.S = obj.S >= 10 ? obj.S : '0' + obj.S;
        returnobj; }}// Let the program run on its own
var t = setInterval(function() {
    var remainTime = comTime('2022/2/1 0:0:0');
    d.innerHTML = remainTime.D;
    h.innerHTML = remainTime.H;
    m.innerHTML = remainTime.M;
    s.innerHTML = remainTime.S;
    if (remainTime.D == '00' && remainTime.H == '00' && remainTime.M == '00' && remainTime.S == '00') {
        clearInterval(t);
    }
    console.log(remainTime);
}, 1000);
Copy the code

I won’t repeat the CSS code and HTML code here. Please leave a comment in the comments section. Finally, I wish you a happy New Year and all the best.