G
G
grenline1231232021-06-28 11:45:48
JavaScript
grenline123123, 2021-06-28 11:45:48

How to link the countdown to a specific product?

It is necessary to show the timer for the end of the promotion on the product list page, how can I change the code below so that it works separately for each of the products, since each has its own time

var countDownDate = new Date("July 1, 2021 04:00:00").getTime();

    var x = setInterval(function() {

    var now = new Date().getTime();
        
    var distance = countDownDate - now;
        
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
        
    document.getElementById("demo").innerHTML = days + "д " + hours + "ч "
    + minutes + "м " + seconds + "с ";
        
    if (distance < 0) {
        clearInterval(x);
    }
    }, 1000);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AleksMedovnik, 2021-06-28
@Medovnik

let countDownDate_1 = new Date("July 1, 2021 04:00:00").getTime();
    let countDownDate_2 = new Date("July 1, 2021 04:00:00").getTime();
    let countDownDate_3 = new Date("July 1, 2021 04:00:00").getTime();


    const timer = (date) => {
      let now = Date.now();

      let distance = date - now;

      let days = Math.floor(distance / (1000 * 60 * 60 * 24));
      let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      let seconds = Math.floor((distance % (1000 * 60)) / 1000);

      document.getElementById("demo").innerHTML = days + "д " + hours + "ч "
        + minutes + "м " + seconds + "с ";

      if (distance < 0) {
        clearInterval(x);
      }
    }

    let x = setInterval(function () {
      timer(countDownDate_1);
      timer(countDownDate_2);
      timer(countDownDate_3);
    }, 1000);

Also, in order not to run the timer many times, you can do it using a loop. That is, loop through all products and start timer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question