HTML/JS如何调整(倒计时)产品数量

HTML/JS How to Adjust (Count Down) Product Quantity

我有一个简单的 html 元素,其中包含一个代表产品数量的数字...

<h1>Product QTY</h1>
<div id=“prod-qty”>
  <div>
    <span class=“qty”>57</span>
    <div class="smalltext">Left In Stock</div>
  </div>  
</div>
  1. 如何使用 JS 使该数字每 15 秒减 1?
  2. 如何用JS让那个数字每15-30随机减1-3 秒?

这应该给你一个起点

var runEvery = 15 * 1000; //seconds;
window.setInterval(function(){
    var elem = $("#prod-qty .qty");
    var decrease = 1;
    var value = +elem.text() - decrease;
    if(value <= 0) {
      value = 0;
    }
    elem.text(value);
}, runEvery);

要为减量和执行频率生成随机值,请检查 reference

这段代码应该可以满足您的需求:

<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> 

每次调用setQty函数,更新数量,减去下一次更新的randomley数量(1-3),setQty的调用以callBack-function开始时间(15-30 秒)。