JS——The time countdown returns day, hour, minute, second

1. Create a new DHMScountDown.js

/**  时分秒倒计时 */
let timer = null;
export default {
    
    
  /**
   * 开始
   * @param callback(Object) 回调函数
   * @param endDate 截至日期
   * @param interval 间隔时间毫秒(默认1秒)
   */
  start: (callback, endDate, interval = 1000) => {
    
    
    if (timer) return;
    timer = setInterval(() => {
    
    
      let now = Date.now();
      let end = new Date(endDate);
      let leftTime = end.getTime() - now;
      let d, h, m, s;
      if (leftTime >= 0) {
    
    
        d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
        h = Math.floor((leftTime / 1000 / 60 / 60) % 24);
        m = Math.floor((leftTime / 1000 / 60) % 60);
        s = Math.floor((leftTime / 1000) % 60);
        callback({
    
    
          d: String(d).length < 2 ? `0${
      
      d}` : `${
      
      d}`,
          h: String(h).length < 2 ? `0${
      
      h}` : `${
      
      h}`,
          m: String(m).length < 2 ? `0${
      
      m}` : `${
      
      m}`,
          s: String(s).length < 2 ? `0${
      
      s}` : `${
      
      s}`,
        });
      } else {
    
    
        clearInterval(timer);
        timer = null;
        return;
      }
    }, interval);
  },
  /** 清理定时器 */
  clear: () => {
    
    
    clearInterval(timer);
    timer = null;
  },
};

2. use

import DHMScountDown from "./DHMScountDown.js"
//开始倒计时
HMScountDown.start(({
     
     d, h, m, s}) => {
    
    
	console.log(`${
      
      d}${
      
      h}:${
      
      m}:${
      
      s}`)
}, "2023-3-7 16:50");

//清除倒计时
HMScountDown.clear()

Guess you like

Origin blog.csdn.net/qq812457115/article/details/129385653