简体   繁体   English

如何在Jquery中实现真正的随机性?

[英]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.

相关问题 我可以使用返回加权布尔值的 function 实现加权随机性吗? - Can I achieve weighted randomness with a function that returns weighted booleans? 如何使用Javascript / Jquery实现这些? - How can i achieve the these with Javascript / Jquery? 如何通过jquery实现“跳转”? - How can I achieve “jumps” with jquery? 如何添加一些随机性来填充此列表? - How can I add some randomness to populating this list? 在这种情况下,如何在jquery中实现限制字符? - How can I achieve a limit character in jquery in this situation? 我如何用Lodash做到这一点? - How can I achieve this with Lodash? 我想用很少的控件作为参数在jquery中创建一个自定义函数。 我该如何实现? - I want to create a custom function in jquery with few controls as parameters. How can I achieve this? 重定向到首页网址后,如何使用Javascript / Jquery实现自动点击? - How can I achieve an autoclick with Javascript / Jquery after being redirected to my homepage url? 如果没有 html 中的 onclick = "showHide (this),但在 jquery 中,如何实现相同的效果? - How can I achieve the same without having the onclick = "showHide (this) in the html, but in jquery? 如何实现像jQuery的slideDown这样的下滑效果,但只使用CSS? - How can I achieve a slide down effect like jQuery's slideDown, but only using CSS?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM