-1

I have a simple html element that contains a number representing product quantity...

<h1>Product QTY</h1>
<div id=“prod-qty”>
  <div>
    <span class=“qty”>57</span>
    <div class="smalltext">Left In Stock</div>
  </div>  
</div>
  1. How can I use JS to decrease that number by 1 every 15 seconds?
  2. How can I use JS to decrease that number by 1-3 randomly every 15-30 seconds?
Yaron
  • 10,166
  • 9
  • 45
  • 65
corey
  • 63
  • 9

2 Answers2

0

This should give you an starting point

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

To generate random values for the decrement and the frequency of the execution check the reference.

james_bond
  • 6,778
  • 3
  • 28
  • 34
0

This code should do what you want:

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

Every time when the function setQty is called, the quantity is updated, a randomley quantity (1-3) is for the next update subtracted and the call to setQty is started with a callBack-function in a randomely time (15-30 s).

Sascha
  • 4,576
  • 3
  • 13
  • 34