以下是一个封装好的倒计时方法,可以满足您的需求:

function countdown(start, end, now = new Date()) {
  const startTime = new Date(start).getTime();
  const endTime = new Date(end).getTime();
  const diff = endTime - startTime;
  
  if (now < startTime) {
    return { days: 0, hours: 0, minutes: 0, seconds: 0 };
  }
  
  const timeElapsed = now - startTime;
  const timeRemaining = diff - timeElapsed;
  
  const days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));
  const hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);
  
  return { days, hours, minutes, seconds };
}

使用方法:

// 假设当前时间为 2022-01-01 12:00:00
const start = '2022-01-01 00:00:00';
const end = '2022-01-02 00:00:00';

const remainingTime = countdown(start, end);

console.log(remainingTime); // { days: 1, hours: 0, minutes: 0, seconds: 0 }

其中,'start' 和 'end' 分别为倒计时的开始时间和结束时间,格式为字符串,例如 '2022-01-01 00:00:00'。'now' 为可选参数,表示当前时间,默认为当前时间。函数返回一个对象,包含天数、小时数、分钟数和秒数。若当前时间早于开始时间,则返回值为 { days: 0, hours: 0, minutes: 0, seconds: 0 }

JavaScript 倒计时函数:封装与使用指南

原文地址: https://www.cveoy.top/t/topic/mk07 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录