倒数计时器问题(倒数3种可能的结果)

时间:2019-03-04 00:56:43

标签: javascript

我正在学习JavaScript,并为各种产品使用倒数计时器。当产品发布时,会通过API给出“ start_time”和“ end_time”。

在到达开始时间之前,它将显示“在X天X小时X分钟X秒内可用”-当到达开始时间但尚未到达结束时间时,它将显示“产品在X天X小时X分钟内打开” X秒”-到达end_time时,将显示“不再可用”。

我让倒数计时器适用于“可用”和“所有人可用”(我希望是正确的)-但我无法显示“产品打开”消息。感谢您的指导。

我在shopify中这样做,但是。我在3种测试产品的开始时间和结束时间中写道,因为我不确定它是否可以与API url配合使用,所以我从API中抓取。

  (function(){
    // API product data
    product1 = {
    "start_time":"2019-04-01T00:30:00.000Z",
    "end_time":"2019-04-01T01:30:00.000Z"
    }

    product2 = { 
    "start_time": "2019-02-26T02:01:54.557Z",
    "end_time":"2020-02-26T02:01:54.557Z"
    }

    product3 = { 
    "start_time": "2019-02-26T02:01:54.557Z",
    "end_time":"2019-03-01T11:24:43.327Z"
    }


  function countdown() {
    countdown().then(function(result) {
      var start_time = result.start_time;
      var end_time = result.end_time;
      // Set the date we're counting down to
      var countDownDate = new Date(start_time).getTime();
      // Set live time period
      var liveDate = new Date(end_time).getTime();

      // Update the count down every 1 second
      var x = setInterval(function() {

        // Get todays date and time
        var now = new Date().getTime();

        // Find the distance between now and the countdown date
        var distance = countDownDate - now;
        var live = liveDate- now;

        // Time calculations for days, hours, minutes and seconds
        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);

        // countdown to launch time
        var counter = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";       

        // Waiting for availability
        if (distance > 0) {

            document.getElementById("countdown-{{product.id}}").innerHTML = "Available in " + counter;        
        }

        // Start live access                            
        if (distance < 0 && distance > end_time) {
            clearInterval(x);
            distance = live;
            document.getElementById("countdown-{{product.id}}").innerHTML = "Product open for " + counter;
        }

        // End time is reached
        if (distance < end_time) {
            document.getElementById("countdown-{{product.id}}").innerHTML = "No more availability";
        }

      }, 1000);            
    }); // end countdown() 
  })();
<p id="countdown-{{product.id}}"></p>

0 个答案:

没有答案