[英]Set random number and then randomly decrease it every 5 second until it reaches 0 (javascript)
我想在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之间的随机数(不多)
在loadRandom
范围之外声明number_objects
。 具有不同功能的显示值。 一次调用此函数以进行初始显示,并在间隔中减小该值并再次显示。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.