javascript - 在给定时间内将随机数倒数到 0

标签 javascript jquery html countdown

我正在创建一个倒计时,我需要将其倒数到 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">&nbsp;</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/

相关文章:

javascript - 在循环vuejs中加载特定的div

javascript - 如何定位灯箱/div 弹出窗口,使其位于 iframe 中视口(viewport)的中心

javascript - 动态创建 Div 并使用参数设置其 onclick 事件

html - 如何使用 HTML5 和 CSS 3 将按钮放置在一个圆圈周围?

javascript - 是否可以在 Javascript 函数中调用 ASP.NET 函数?

javascript - 1000hz Bootstrap 验证器数据切换 ="validator"不工作

javascript - 如何使用 javascript/jQuery 根据内部 div 元素内容/值对 div 元素进行排序?

javascript - 使用 Angular 4 将页眉/页脚与内容分开

html - 内容 div 没有填满剩余空间

javascript - Vue 实异常(exception)部的“vm”对象并在方法内部调用 Mounted undefined