如何将此间隔从每2秒创建为随机X-X秒?另外,如何将每2个增量的增量更改为随机X-X?如果您发现我的代码存在缺陷或需要改进,请告诉我,如果愿意,请使用单独的代码。非常感谢。
<div id="counter"></div>
<script type="text/javascript">
var START_DATE = new Date("January 1, 2012 12:00:00"); // put in the starting date here
var INTERVAL = 2; // in seconds
var INCREMENT = 2; // increase per tick
var START_VALUE = 5000; // initial value when it's the start date
var count = 0;
window.onload = function()
{
var msInterval = INTERVAL * 2000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = count;
setInterval(
"count += INCREMENT; document.getElementById('counter').innerHTML = count;", msInterval);
}
</script>
答案 0 :(得分:1)
两个数字之间的随机数
var min = 1000, max = 10000;
var msInterval = Math.floor(Math.random() * (max - min + 1)) + min;
在setInterval中使用闭包不要传递为字符串
setInterval(function(){
count += INCREMENT;
document.getElementById('counter').innerHTML = count;
}, msInterval);
小提琴,我编辑了一些重要值以使其更快http://jsfiddle.net/sabithpocker/8CpaF/
答案 1 :(得分:0)
var x = Math.floor(Math.random()* 3 + 2;
<script type="text/javascript">
var START_DATE = new Date("January 1, 2012 12:00:00"); // put in the starting date here
var INTERVAL = 2;
var INCREMENT = Math.floor(Math.random()*3)+2;
var START_VALUE = 5000; // initial value when it's the start date
var count = 0;
window.onload = function()
{
var msInterval = INTERVAL * 2000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = count;
setInterval(
"count += INCREMENT; document.getElementById('counter').innerHTML = count;", msInterval);
}
</script>