gpt4 book ai didi

javascript - 使用最小值和最大值随机化 setInterval

转载 作者:行者123 更新时间:2023-11-30 09:27:53 26 4
gpt4 key购买 nike

我有以下代码:

var myVar;    
function showDiv() {
var random = Math.floor(Math.random() * $('.notification').length);
$('.notification').eq(random).fadeIn(200).delay(3000).fadeOut(200);
}
function stopFunction() {
clearInterval(myVar); // stop the timer
}
$(document).ready(function () {
myVar = setInterval(showDiv, 2000);
});

我现在尝试的是,将 setInterval 随机化,但在最小 2000 和最大 10000 的范围内。

这是我的 fiddle :https://jsfiddle.net/gkq21ppt/

最佳答案

您将需要使用 setTimeout 以 2000 到 10000 之间的随机值作为时间间隔来调用 showDiv。这可以在 createRandomInterval 函数中完成,以便您可以在 showDiv 函数中重用它,以便下次在随机时间间隔后执行。

示例:

var myVar;    
function showDiv(){
var random = Math.floor(Math.random() * $('.notification').length);
$('.notification').eq(random).fadeIn(200).delay(3000).fadeOut(200);
createRandomInterval();
}

function createRandomInterval(){
setTimeout(showDiv, 2000+ Math.random() * 8000);
}
$(document).ready(function(){
createRandomInterval();
});
.notification {
width: 200px;
height: 50px;
background-color: yellow;
border: 1px solid rgba(0,0,0,0.2);
margin-bottom: 5px;
display: flex;
justify-content: center;
align-items: center;
display: none;/* hide initially so that fadIn() fadeOut() will work
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="first" class="notification">first</div>
<div id="second" class="notification">second</div>
<div id="third" class="notification">third</div>
<div id="fouth" class="notification">fourth</div>
<div id="fifth" class="notification">fifth</div>

关于javascript - 使用最小值和最大值随机化 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48298667/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com