Несколько методов создания таймера обратного отсчета в JavaScript

  1. Использование setInterval():

    function countdown(targetDate) {
    const timer = setInterval(() => {
    const now = new Date().getTime();
    const distance = targetDate - now;
    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);
    console.log(`${days}d ${hours}h ${minutes}m ${seconds}s`);
    if (distance < 0) {
      clearInterval(timer);
      console.log('Countdown finished');
    }
    }, 1000);
    }
    // Example usage:
    const targetDate = new Date('2024-01-01').getTime();
    countdown(targetDate);
  2. Использование setTimeout():

    function countdown(targetDate) {
    const now = new Date().getTime();
    const distance = targetDate - now;
    if (distance < 0) {
    console.log('Countdown finished');
    return;
    }
    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);
    console.log(`${days}d ${hours}h ${minutes}m ${seconds}s`);
    setTimeout(() => {
    countdown(targetDate);
    }, 1000);
    }
    // Example usage:
    const targetDate = new Date('2024-01-01').getTime();
    countdown(targetDate);
  3. Использование requestAnimationFrame():

    function countdown(targetDate) {
    const now = new Date().getTime();
    const distance = targetDate - now;
    if (distance < 0) {
    console.log('Countdown finished');
    return;
    }
    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
    const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((distance % (1000 * 60)) / 1000);
    console.log(`${days}d ${hours}h ${minutes}m ${seconds}s`);
    requestAnimationFrame(() => {
    countdown(targetDate);
    });
    }
    // Example usage:
    const targetDate = new Date('2024-01-01').getTime();
    countdown(targetDate);