将给定时间内的随机数递减为0

问题描述 投票:0回答:2

我正在创建一个倒计时,我需要将其倒计时至0,但要使用随机数。

从每秒4分钟的秒倒数,但我需要显示一个介于300到390之间的值,在上述4分钟内的随机数显示为0。

我创建了随机数倒计时,但仍然无法弄清楚如何在给定时间内将其变为0。

<script>
var count = 350; //this is a random value between(300-390)
var timer = setInterval(function() {
//this will generate number between 0 to 10 and reduce it from count randimly
    count -= Math.floor(Math.random()*9);
    //set it to html element
    jQuery('#maindvpart').html(count);

//when number become 0
    if( count <= 0) {
        jQuery('#maindvpart').html(0);
        count = 0;
        clearInterval(timer);
    }

//but i need to run this countdown within 4 minutes
//(so when 0 minutes ends above count should zero, until 0 it should count down from random number)

},1000);
</script>
<div id="maindvpart">&nbsp;</div>

任何人都有想法或例子,如何做到这一点,谢谢

javascript jquery html countdown
2个回答
1
投票

您的“计时器”每秒运行一次。当您执行“ count-= Math.floor(Math.random()* 9);”时,它减少“ count”变量值的速度更快,因此,您始终会比4分钟快得多地达到“ count <= 0”。如果要运行计时器4分钟,则需要每秒运行计时器-240次,并“显示随机数”,但不要从计数中减去该随机数。这有帮助吗?

使用示例进行编辑,希望它可以将您引向您的目标:

<script>
var count = 240; //4 minutes
var displayNumber = 350; //or whatever number you want to start with
var timer = setInterval(function() {
    //this will generate number between 0 to 10 and reduce it from displayNumber randomly
    displayNumber -= Math.floor(Math.random()*9);
    count--;
    console.log(displayNumber);

    // exit if either the display number is <= 0 or the time is up
    if( displayNumber <= 0 || count <= 0) {
        console.log(0);
        displayNumber = 0;
        clearInterval(timer);
    }
},1000);
</script>

1
投票

解决方案1:

简单地修改时间间隔,之后将随机数减少单位步长(即:1),以指示时间到时随机数等于0所需的时间步长。等式为:{从rand#减去1之前的延迟(以秒为单位=直到rand#达到0(以秒为单位)/ rand#所经过的时间}

ex:

1 rand#= 300,需要递减计数直到2分钟(120秒)达到0,然后300需要每120/300 sec递减1。

var count = 300 // your randomly generated number; 
var time = 60 //time elapsed before the random number to equal 0;
var timer = setInterval(function() {
count = count -1;
console.log(count);
if( count <= 0) {
    count = 0;
    clearInterval(timer);
    }
},(time/count)*1000);

解决方案2:

修改单位步长,在指定的时间过去后,每秒减少随机数,直到它达到0。等式为:{随机数递减步长= rand#/经过时间直到rand#达到0(以秒为单位)}

ex:

1 rand#= 300,需要递减计数直到1分钟(60秒)达到0,然后300需要每1秒递减300/60递减

var count = 300 // your randomly generated number; 
var time = 20 //time elapsed before the random number to equal 0;
var decrementStep=count/time; 

var timer = setInterval(function() {
count = count - decrementStep;
console.log(count);
if( count <= 0) {
    count = 0;
    clearInterval(timer);
    }
},1000);
© www.soinside.com 2019 - 2024. All rights reserved.