[英]How to make a JS Counter & Reset?
I am trying to make a JS
counter to reach a random number and reset it self once it reaches the number and repeat again in 5 seconds. 我正在尝试使JS
计数器达到随机数,并在达到该数字后自行重置,并在5秒钟内再次重复。
For example : Random Number is 0.05. 例如 :随机数是0.05。
0.00 > 0.01 > 0.02 > 0.03 > 0.04 > 0.05 > 0.00
<div id="current">0</div>
JS JS
var randomNum = Math.random();
if ( current <= randomNum ) {
for (current = 0; current < randomNum; current+=0.01) {
setInterval(function(){
current += .01;
},1000); } }
else {
current = 0;
}
You could use a closure over the variables and make a check inside of the callback, if greater then the wanted result. 您可以对变量使用闭包,并在回调内部进行检查(如果大于所需的结果)。
This proposal uses setInterval
for counting and setTimeout
for the waiting time of 5 sec and the restarting with a new random value. 该建议使用setInterval
进行计数,并使用setTimeout
等待5秒钟的等待时间,然后使用新的随机值重新启动。
function startInterval() { var randomNum = Math.floor(Math.random() * 8) + 2, current = 0, interval = setInterval(function() { current += .01; if (current > randomNum / 100) { current = 0; clearInterval(interval); setTimeout(startInterval, 5000); } document.getElementById('current').innerHTML = current.toFixed(2); }, 1000); } startInterval();
<div id="current">0</div>
Keep a counter variable outside of the loop and then simply clear it, when the desired value is reached. 将计数器变量保留在循环外,然后在达到所需值时简单地将其清除。
var randomNum = Math.random() * 25; var currentValue = 0; var counter; counter = setInterval(function() { if (currentValue < randomNum) { //Carefull with "0.1" as JavaScript doesn't like it! currentValue = (currentValue * 10 + 1) / 10 } if (currentValue > randomNum) { currentValue = randomNum; clearInterval(counter); } console.log(currentValue, '/', randomNum) }, 1000 / 60)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.