How to achieve countdown effect in js

How to do countdown in js is actually very simple. Without further ado, let's serve the food directly


Use new Date() to get the current time, the Date.parse() method parses a string representing a certain date, and returns the date object from 1970-1-1 00:00:00 UTC to the date object (the UTC time of the date object ) in milliseconds. Then, find the difference between the two times. Here you can also use the getTime() method to get the number of milliseconds between the present tense and the end time.
Convert time difference to display in days, hours, minutes and seconds. Mainly use %the modulo operation. Gets the number of milliseconds to the end time (remaining milliseconds), divides by 1000 to get the remaining seconds, divides by 60 to get the remaining minutes, and divides by 60 to get the remaining hours. Divide by 24 to get the number of days remaining. Remaining seconds diff/1000 modulo 60 to get seconds and remaining minutes. number. diff/(1000 * 60) modulo 60 gets the minutes and remaining hours diff/(1000 * 60 * 60) mod 24 gets the hours.

getPart(endTime) {
    //获取当前时间戳并换算为秒做单位
    const current = Date.parse(new Date()) / 1000
    //时间戳相差多少秒
    let diff = endTime - current
    //判断是否过时
    if (diff > 0) {            
      let d = Math.floor(diff / (3600 * 24))        //获取天数
      let h = Math.floor((diff % (3600 * 24)) / (60 * 60))        //获取时
      let m = Math.floor(((diff % (3600 * 24)) % (60 * 60)) / 60)        //获取分
      let s = Math.floor(diff % 60)        //获取秒
      d = d < 10? "0" + d : d;
      h = h < 10? "0" + h : h;
      m = m < 10? "0" + m : m;
      s = s < 10? "0" + s : s;
      let _diffData = [d, h, m, s]
    } else {
      let _diffData = ["00", "00", "00","00"];
    return _diffData;
      
setInterval(getPart(), 1000); 

To encapsulate the countdown, you can use the setInterval() method to call the function to realize the countdown.

If you want to stop the countdown, you can use the clearInterval() method.

If there is any error in the description, please correct me!

Guess you like

Origin blog.csdn.net/m0_70015558/article/details/124644898