Node.js编写报时器,精度高、性能高

发布时间 2023-03-27 10:42:50作者: 项希盛

Node.js编写的报时器,精度高、性能高

// Function to print the current time every minute on the 0th second and with millisecond precision
function printTime(interval, oldDate) {
  // Get the current date and time
  const nowDate = new Date()
  const nowNextTime = Math.ceil(nowDate.getTime() / interval);
  const oldNextTime = Math.ceil(oldDate.getTime() / interval);
  // Calculate the delay until the next minute by subtracting the current time from the next minute and subtracting 1 second (1000 milliseconds) to account for the time it takes to print the time and schedule the next call
  const delay = (nowNextTime * interval - nowDate.getTime()) / 2;
  if (oldNextTime < nowNextTime) {
    console.log(nowDate)
  }
  // Schedule a call to the printTime function after the calculated delay
  setTimeout(() => {
    // Schedule the next call to the printTime function
    printTime(interval, nowDate);
  }, delay);
}

// Start the printing process by calling the printTime function for the first time
printTime(10000, new Date())