简体   繁体   中英

Javascript SetInterval and get value Math.random

I have just created random number. My problems is how to get value random in id and how to set price changes automatically every 5 seconds and the fluctuation amplitude less than +/- 5% compared to the current, I don't know use the setinterval function everybody help me

My code Random Price :

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);

I think you can understand this code. I tried to keep your code. The key is to use setInterval function.

 <!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> 

My interpretation of your question: all elements to start with a random value between 0 and 99.99, and then every five seconds one randomly selected element is to be updated, changing its value by a random amount within 5% of its current value. (If you want to update every element every five seconds then change the random selection to be a loop instead.)

For simplicity in the demo snippet (click "Run code snippet" to see it work), I've used a group of <li> elements which I select with .querySelectorAll("li") , but if you really want to do it using element IDs you could say .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> 

Note that five second intervals seemed too slow for a demo, so I've used one second (1000ms) here.

Further reading:

Hope this will help.

<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

It took me a while to work around the recursion issues I was running into, before I came up with a better solution.

 //<![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> 

Should work now!

After you create a new RandNumMaker(min, max) then you can set randomNumMarkerInstance.decimalPlaces , randomNumMakerInstance.withinPercent and randomNumMakerInstance.secondsInterval using simple assignment. randomNumMakerInstance.setDiv(div) starts it. randomNumMakerInstance.stop() stops it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM