Javascript SetInterval并获取值Math.random

时间:2017-10-25 02:21:34

标签: javascript jquery node.js

我刚刚创建了随机数。我的问题是如何在id中随机获取值以及如何每5秒自动设置价格变化,并且波动幅度小于当前的+/- 5%,我不知道使用setinterval函数每个人都帮助我

我的代码随机价格:

function generateRandomNumber(min,max) {
    return (Math.random() * (max - min) + min).toFixed(2);

};
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);

4 个答案:

答案 0 :(得分:1)

我认为你可以理解这段代码。 我试图保留你的代码。 关键是使用setInterval函数。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<script>
    function generateRandomNumber(min,max) {
        return (Math.random() * (max - min) + min).toFixed(2);
    };
    function assignData(){
        document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
        document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
        document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
        document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
        document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
        document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
        document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
        setInterval(assignData, 5000);  //every 5 seconds
    }
    
</script>

<body onload="assignData()">
    <h2 id="price1"></h2>
    <h2 id="price2"></h2>
    <h2 id="price3"></h2>
    <h2 id="price4"></h2>
    <h2 id="price5"></h2>
    <h2 id="price6"></h2>
    <h2 id="price7"></h2>
</body>
</html>

答案 1 :(得分:1)

我对你的问题的解释:所有元素以0到99.99之间的随机值开始,然后每隔5秒一个随机选择的元素将被更新,随机改变其值在其当前值的5%以内。 (如果要每五秒更新一个元素,请将随机选择更改为循环。)

为了简化演示代码段(点击“运行代码段”以查看它是否有效),我使用了一组<li>元素,我选择.querySelectorAll("li"),但如果你真的想要使用你可以说.querySelectorAll("#price1,#price2,#price3,#price4,#price5,#price6,#price7")的元素ID来做到这一点。

function generateRandomNumber(min,max) {
    return (Math.random() * (max - min) + min).toFixed(2);
}

// get list of elements:
var elements = document.querySelectorAll("li");
// populate all elements initially:
[].forEach.call(elements, function(el) {
  el.innerHTML = generateRandomNumber(0,99.99);
});

// update an element at random every  second:
setInterval(function update() {
  var element = elements[Math.floor(Math.random() * elements.length)];
  var currentVal = +element.innerHTML;
  element.innerHTML = generateRandomNumber(currentVal * 0.95, currentVal * 1.05);
}, 1000);
<ul>
  <li></li><li></li><li></li><li></li><li></li><li></li><li></li>
</ul>

请注意,对于演示来说,五秒间隔似乎太慢了,所以我在这里使用了一秒钟(1000毫秒)。

进一步阅读:

答案 2 :(得分:0)

希望这会有所帮助。

<body>
  <p id="price1"></p>
    <p id="price2"></p>
    <p id="price3"></p>
    <p id="price4"></p>
    <p id="price5"></p>
    <p id="price6"></p>
    <p id="price7"></p>
</body>
<script>

    //set initial random number for the elements
    document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
    document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
    document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
    document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
    document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
    document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
    document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);

    //set random number to elements with fluctuation +/- 5%
    setRandomToElements()

    function generateRandomNumber(min,max) {
        return (Math.random() * (max - min) + min).toFixed(2);
    };

    function setRandomToElements(){       
    //get current prices
    var currentPrice1 = parseInt(document.getElementById('price1').innerHTML);
    var currentPrice2 = parseInt(document.getElementById('price2').innerHTML);
    var currentPrice3 = parseInt(document.getElementById('price3').innerHTML);
    var currentPrice4 = parseInt(document.getElementById('price4').innerHTML);
    var currentPrice5 = parseInt(document.getElementById('price5').innerHTML);
    var currentPrice6 = parseInt(document.getElementById('price6').innerHTML);
    var currentPrice7 = parseInt(document.getElementById('price7').innerHTML);

    var fluctuation = 0.05;//5%

    //random new numbers +/-5% current price
    document.getElementById('price1').innerHTML = generateRandomNumber(currentPrice1-(currentPrice1*fluctuation), currentPrice1+(currentPrice1*fluctuation));
    document.getElementById('price2').innerHTML = generateRandomNumber(currentPrice2-(currentPrice2*fluctuation), currentPrice2+(currentPrice2*fluctuation));
    document.getElementById('price3').innerHTML = generateRandomNumber(currentPrice3-(currentPrice3*fluctuation), currentPrice3+(currentPrice3*fluctuation));
    document.getElementById('price4').innerHTML = generateRandomNumber(currentPrice4-(currentPrice4*fluctuation), currentPrice4+(currentPrice4*fluctuation));
    document.getElementById('price5').innerHTML = generateRandomNumber(currentPrice5-(currentPrice5*fluctuation), currentPrice5+(currentPrice5*fluctuation));
    document.getElementById('price6').innerHTML = generateRandomNumber(currentPrice6-(currentPrice6*fluctuation), currentPrice6+(currentPrice6*fluctuation));
    document.getElementById('price7').innerHTML = generateRandomNumber(currentPrice7-(currentPrice7*fluctuation), currentPrice7+(currentPrice7*fluctuation));

    setInterval(setRandomToElements, 5000); 
 }

</script>

Fiddle

答案 3 :(得分:0)

在我提出更好的解决方案之前,我花了一些时间来解决我遇到的递归问题。

&#13;
&#13;
//<![CDATA[
// external.js
function RandNumMaker(min, max, withinPercent, secondsInterval, decimalPlaces){
  this.withinPercent = withinPercent || 5;
  this.secondsInterval = secondsInterval || 5;
  this.decimalPlaces;
  if(decimalPlaces){
    this.decimalPlaces = decimalPlaces;
  }
  var t = this, ia = [];
  function rb(mn, mx){
    return mx-Math.random()*(mx-mn);
  }
  var pn = rb(min, max);
  function rn(){
    var p = 1;
    if(Math.floor(Math.random()*2) === 1)p = -1
    return  p*(Math.floor(Math.random()*t.withinPercent)+1)/100*pn;
  }
  function rf(){
    var r, d = t.decimalPlaces;
    pn += rn();
    if(pn < min || pn > max){
      return rf();
    }
    r = pn;
    if(d)r = (Math.floor(Math.round(Math.pow(10, d+1)*r)/10)/Math.pow(10, d)).toFixed(d);
    return r;
  }
  this.setDiv = function(div){
    div.innerHTML = rf(); ia = [];
    var iv = setInterval(function(){
      div.innerHTML = rf();
    }, this.secondsInterval*1000);
    ia.push(iv);
    return this;
  }
  this.stop = function(){
    for(var i=0,l=ia.length; i<l; i++){
      if(ia[i]){
        clearInterval(ia[i]);
      }
    }
    ia = [];
    return this;
  }
}
var doc, bod, C, E, N, old = onload; // for use on other loads
onload = function(){
if(old)old();
doc = document; bod = doc.body;
C = function(tag){
  return doc.createElement(tag);
}
E = function(id){
  return doc.getElementById(id);
}
N = function(className, inElement){
  var ii = inElement || doc;
  var cN = ii.getElementsByClassName(className);
  if(cN){
    return cN;
  }
  var tn = ii.getElementsByTagName('*');
  for(var i=0,e,a=[],l=tn.length; i<l; i++){
    e = tn[i];
    if(e.className && e.className === className)a.push(e);
  }
  return a;
}
var sr = new RandNumMaker(0, 99.99), sl = N('slow');
var fr = new RandNumMaker(0, 99.99), fs = N('fast');
sr.decimalPlaces = 2;
fr.secondsInterval = 0.1; fr.withinPercent = 5;
for(var i=0,l=sl.length; i<l; i++){
  sr.setDiv(sl[i]);
}
for(var i=0,l=fs.length; i<l; i++){
  fr.setDiv(fs[i]);
}
}
//]]>
&#13;
/* extrnal.js */
html,body{
  padding:0; margin:0;
}
body{
  background:#000; overflow-y:scroll;
}
.main{
  width:940px; background:#fff; padding:20px; margin:0 auto;
}
&#13;
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <meta name='viewport' content='width=device-width' />
    <title>test</title>
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
  <body>
    <div class='main'>
      <div class='slow'></div>
      <div class='slow'></div>
      <div class='slow'></div>
      <div class='slow'></div>
      <div class='slow'></div>
      <div class='slow'></div>
      <div class='slow'></div>
      <hr />
      <div class='fast'></div>
      <div class='fast'></div>
      <div class='fast'></div>
      <div class='fast'></div>
    </div>
  </body>
</html>
&#13;
&#13;
&#13;

现在应该工作!

创建new RandNumMaker(min, max)后,您可以使用简单分配设置randomNumMarkerInstance.decimalPlacesrandomNumMakerInstance.withinPercentrandomNumMakerInstance.secondsIntervalrandomNumMakerInstance.setDiv(div)启动它。 randomNumMakerInstance.stop()阻止了它。