JavaScript SetInterval和获取值Math.random

3

我刚刚创建了一个随机数。我的问题是如何在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);

{btsdaf} - nnnnnn
{btsdaf} - Honda hoda
{btsdaf} - aquaman
函数autoChage() { function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min)) + min; } document.getElementById('demo').innerHTML = (getRndInteger(1000,10000000)).toLocaleString(); }setInterval(autoChage , 5000); - Honda hoda
4个回答

0

我认为你可以理解这段代码。 我试图保留你的代码。 关键是使用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>


0

我的理解是:所有元素都以0到99.99之间的随机值开始,然后每五秒钟随机选择一个元素进行更新,使其值在当前值的5%范围内随机变化。(如果您想每五秒钟更新每个元素,则将随机选择更改为循环。)

为了简化演示代码段(点击“运行代码片段”查看它的工作方式),我使用了一组用<li>元素选择的元素,使用.querySelectorAll("li"),但如果您真的想使用元素ID来完成它,您可以说.querySelectorAll("#price1,#price2,#price3,#price4,#price5,#price6,#price7")

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毫秒)。
进一步阅读:
  • {{link1:.querySelectorAll()}}
  • {{link2:Array .forEach() 方法}}
  • {{link3:Function.prorotype.call()}}
  • {{link4:Math.floor()}}
  • {{link5:一元加运算符}}

0

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

//<![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]);
}
}
//]]>
/* extrnal.js */
html,body{
  padding:0; margin:0;
}
body{
  background:#000; overflow-y:scroll;
}
.main{
  width:940px; background:#fff; padding:20px; margin:0 auto;
}
<!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>

现在应该可以工作了!

创建new RandNumMaker(min, max)之后,您可以使用简单的赋值设置randomNumMarkerInstance.decimalPlacesrandomNumMakerInstance.withinPercentrandomNumMakerInstance.secondsIntervalrandomNumMakerInstance.setDiv(div)开始它。 randomNumMakerInstance.stop()停止它。


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>

小提琴


1
Way off of the 5% request. - StackSlave

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接