设置随机数,然后每5秒随机减少一次,直到达到0(javascript)

时间:2015-04-06 14:22:03

标签: javascript jquery html random

我想在200到300之间设置一个随机数,然后每隔5秒逐步减少它,直到它达到0。

我只有开始设置初始数字

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

如何实现这种随机减少直到0?

注意:我想每次减少一个随机数,范围从1到5(不多)

1 个答案:

答案 0 :(得分:2)

number_objects范围之外宣布loadRandom。有不同的功能确实显示值。为初始显示调用此函数一次,在间隔中,减小该值并再次显示。

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