我正在创建一个倒计时,我需要将其倒数到 0,但以随机数的形式。
Ex-从 4 分钟开始倒计时,但我需要显示 300 到 390 之间的值,倒计时到 0,并在 4 分钟以上的时间内使用随机数。
我创建了随机数倒计时,但仍然无法弄清楚如何在给定时间内将其变为 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"> </div>
任何人都有想法或示例如何做到这一点,谢谢
最佳答案
您的"timer"
每秒运行一次。当你这样做时"count -= Math.floor(Math.random()*9);"
,它会更快地减少“count”变量值,因此您将始终达到 "count <= 0"
比4分钟快得多。如果您想运行计时器 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>
关于javascript - 在给定时间内将随机数倒数到 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60332708/