[英]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. 我正在尝试编写一个小脚本,该脚本每25到60秒随机地在页面上放置一个项目。
The below code will randomly add the div to my page, but every occurrence after that is executed at the exact same time. 下面的代码将div随机添加到我的页面中,但是此后的每次匹配都在同一时间执行。
For instance, if the script begins at 44 seconds, it will add a new div every 44 seconds, and not randomly. 例如,如果脚本在44秒开始,它将每44秒而不是随机地添加一个新的div。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.