按特定日期倒计时数量

时间:2017-06-21 20:44:18

标签: javascript countdown

目前使用以下代码,但问题是数量会刷新每个页面加载。基本上需要从100开始,并在特定日期倒计时到0。

    <h1>Product QTY</h1>
<div id="prod-qty">
  <div>
    <span class="qty" id="qty"></span>
    <div class="smalltext">Left In Stock</div>
  </div>  
</div>

<script>
    var qty = 57
    var qtyId = document.getElementById("qty");

    setQty(qty);

    function setQty(qty)
    {
        qtyId.innerHTML = qty;

        if (qty==0) return;

        var parts = Math.floor((Math.random() * 3) + 1);
        if (parts > qty) parts = qty;

        var msec =  Math.floor(((Math.random() * 15) + 15)*1000);

        qty -= parts;

        setTimeout(function() {
            setQty(qty);
        }, msec)
    }
</script> 

2 个答案:

答案 0 :(得分:0)

这有点蹩脚,但表明你可以计算出已经过去的每一分钟所经过的时间并扣除一部分。

&#13;
&#13;
/* starting quantity */
var qty = 100;
var qtyId = document.getElementById("qty");

/* the start time: June 21, 2017 2:15 PM */
var startDate = new Date(2017, 5, 21, 14, 15);

/* The time now, minus the start time. Divide by 1000 to get seconds instead of milliseconds */
var elapsed = (Date.now() - startDate.getTime()) / 1000;

/* adjust the start quantity by some amount. In this case, just take the number of seconds and divide by 60 to get the number of minutes. So remove a part for every minute that has passed. */
qty -= parseInt(elapsed / 60);

/* now do everything you did before */
setQty(qty);

function setQty(qty) {
  qtyId.innerHTML = qty;

  if (qty == 0) return;

  var parts = Math.floor((Math.random() * 3) + 1);
  if (parts > qty) parts = qty;

  var msec = Math.floor(((Math.random() * 15) + 15) * 1000);

  qty -= parts;

  setTimeout(function() {
    setQty(qty);
  }, msec)
}
&#13;
<h1>Product QTY</h1>
<span id="qty"></span>
<span>Left In Stock</span>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用Jonas建议并使用LocalStorage实际上可能更容易。这是一个例子: https://lab-jesjbhtqfh.now.sh

有关LocalStorage的文档: https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage