简体   繁体   中英

How can I achieve true randomness in Jquery?

I am trying to write a small script that will randomly place an item on my page every 25 to 60 seconds.

The below code will randomly add the div to my page, but every occurrence after that is executed at the exact same time.

For instance, if the script begins at 44 seconds, it will add a new div every 44 seconds, and not randomly.

How can I achieve true randomness?

var contentDiv = ['firstDiv','secondDiv'];
function popDiv(min, max) {
    var timedDiv =  contentDiv[Math.floor(Math.random() * (max - min + 1) + min)];
    jQuery( "#" + timedDiv ).fadeIn( "slow" ).delay(4000).fadeOut("slow");
}

popDiv(1, contentDiv.length - 1)

setInterval(function(){
    popDiv(1, contentDiv.length - 1);
},  
Math.round(Math.random() * (60000 - 15000)) + 15000);

Here's the general principle:

let maxTime = 60000,
    minTime = 25000,
    doSomething = function () {
      // do something...
      setTimeout(function(){
        doSomething();
      }, Math.random() * (maxTime - minTime) + minTime)
   };
doSomething();

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