Time deviation problem and solution of JavaScript countdown

Countdown is a common function in front-end development, but the countdown implemented using the setTimeout and setInterval methods has a serious problem: time deviation. This is caused by the event loop mechanism of JavaScript. This article will explain the causes of time deviation in detail and provide solutions.

Reasons for time deviation

In JavaScript, the setTimeout and setInterval methods work by adding callback functions to an event queue and executing them after a specified interval. However, since JavaScript is single-threaded, these callback functions will only be executed when the execution stack is empty.

This means that if there is other code currently executing, or the browser's performance is limited, the callback function may not be executed within the expected time, resulting in timing skew. This is especially obvious in situations where high-precision countdown is required, such as the countdown to the end of bidding on an auction website.

How to solve time deviation

In order to solve the problem of time deviation, we can use the following methods:

  1. Use requestAnimationFrame: requestAnimationFrame is a high-precision timer provided by the browser, which can execute a callback function before each frame is rendered. This ensures that the callback function is executed when the page is rendered, reducing time deviation.
// 代码
function countdownWithRAF(targetDate) {
  const now = new Date().getTime();
  const difference = targetDate - now;
  const remainingTime = {
    days: Math.floor(difference / (1000 * 60 * 60 * 24)),
    hours: Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
    minutes: Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)),
    seconds: Math.floor((difference % (1000 * 60)) / 1000),
  };

  // 更新倒计时显示
  updateCountdownDisplay(remainingTime);

  if (difference > 0) {
    requestAnimationFrame(() => countdownWithRAF(targetDate));
  }
}

const targetDate = new Date('2023-12-31').getTime();
countdownWithRAF(targetDate);
  1. Using Web Workers: Web Workers allow JavaScript code to be executed in a separate thread, avoiding blocking of the main thread. With Web Workers, we can achieve a more precise countdown that is not affected by the execution time of the main thread.
// 代码
// 在 Web Worker 中执行倒计时逻辑
const worker = new Worker('countdown-worker.js');
worker.postMessage(targetDate);

// 主线程监听 Web Worker 的消息
worker.onmessage = (event) => {
  const remainingTime = event.data;
  updateCountdownDisplay(remainingTime);
}

In actual projects, choose an appropriate method to solve the time deviation problem according to your needs to ensure the accuracy and stability of the countdown function. These methods can help you eliminate time deviations caused by the event execution mechanism and make the countdown function more reliable.

Guess you like

Origin blog.csdn.net/JaneLittle/article/details/132433996