Q:

Set random number and then randomly decrease it every 5 second until it reaches 0 (javascript)

I would like to set a random number between 200  and 300 and then randomly decrease it, step by step every 5 seconds, until it reaches 0.
I only have the beginning where i set the initial number
<div id="object_nb"></div>

<script>
function loadRandom() {
     var number_objects = 200 + Math.floor(Math.random() * 100);
      $('#object_nb').text(number_objects);
}
loadRandom(); // initial display
setInterval(function() {
     ???????? // it executes a random decrease every 5sec
  },5000);
</script>

How can I achieve this random decrease until 0 ?
Note: i would like to decrease each time the number by a random number ranging from 1 to 5 (not more)

A:

Declare number_objects outside loadRandom scope. Have a different function do display the value. Call this function once for initial display and in the interval, decrease the value and display it again.
var number_objects; // value in global scope
var displayObject = $('#object_nb'); // fetch object only once, better performace

function loadRandom() {
    number_objects = 200 + Math.floor(Math.random() * 100);
}
function decreaseRandom() {
    // decrease the value by randomly generated value in range 1 - 5
    number_objects -= Math.floor(Math.random() * 5) + 1;        
}
function showRandom() {
    // show / update the value
    displayObject.text(number_objects);
}
loadRandom(); // load the value
showRandom(); // initial display
var interval = setInterval(function () {
    decreaseRandom();
    // display (update) it
    showRandom();
    if(number_objects <= 0) {
        // clear interval when number of objects gets to, or below, 0
        clearInterval(interval);
    }
}, 5000);

