-1

如何将此间隔从每 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>
4

2 回答 2

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/

于 2012-06-25T23:22:55.227 回答
0
  • 要生成 2 到 5 之间的数字,请使用

var x = Math.floor(Math.random()*3+2;

  • 如果它掷出 0 则得到 2,如果掷出 3 则得到 5。
<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>
于 2012-06-25T23:19:11.187 回答