gpt4 book ai didi

javascript - Jquery .each() 和 SetTimeout 随机时间

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:40:16 25 4
gpt4 key购买 nike

长话短说,我知道为什么 setTimeout 在 .each 函数中不起作用,但我试图开始工作的情况有点复杂。

这次我有两个循环,一个内部循环和一个外部循环。必须按照这个确切的顺序执行操作,否则结果将不正确,这意味着每个 SetTimeout() 都必须停止其他所有操作。每个函数的超时时间也需要是随机的。

// First Loop
$('.items').each(function(e) {
// Something to do
setTimeout(function() {
// Code that does it

// Something else to do
setTimeout(function() {
// Code that does it

// Second Loop
$('.inner-items').each(function(e) {
// Something to do
setTimeout(function() {
// Code that does it

// Something else to do
setTimeout(function() {
// Code that does it

// Why not a third
setTimeout(function() {
// Code that does it
}, Math.random());
}, Math.random());
}, Math.random());
});
}, Math.random());
}, Math.random());
});

最佳答案

这可能行得通。尚未测试,但想法是从 0 的等待时间开始,然后每次您想“停止”该功能时,您实际上只是在等待时间中添加一个新的随机数,因此每个 setTimeout 都在等待所有在它之前添加的时间以及新添加的随机时间。

此外,重要的是,在您的第二个循环中,您正在遍历您当前迭代的项目的子项而不是所有 .inner-items。我添加了 $(this).find('.inner-items') 来执行此操作。

var waitTime = 0;

// First Loop
$('.items').each(function(e) {

// add to wait time
waitTime += Math.random();

// Something to do
setTimeout(function() {
// Code that does it
}, waitTime);

// add to wait time
waitTime += Math.random();

// Something else to do
setTimeout(function() {
// Code that does it
}, waitTime);

// Second Loop
$(this).find('.inner-items').each(function(e) {

// add to wait time
waitTime += Math.random();

// Something to do
setTimeout(function() {
// Code that does it
}, waitTime);

// add to wait time
waitTime += Math.random();

// Something else to do
setTimeout(function() {
// Code that does it
}, waitTime);

// add to wait time
waitTime += Math.random();

// Why not a third
setTimeout(function() {
// Code that does it
}, waitTime);
});
});

编辑

刚刚测试过,似乎有效。每次添加时我至少添加了 500 和 2000,以便更好地可视化顺序和随机触发的事件。

此外,我不确定您所说的 “setTimeout 在 .each 函数中不起作用” 是什么意思。但是通过使用自执行函数,我可以获得正在迭代的当前项并在 setTimeout 中使用。

https://codepen.io/RyanGoree/pen/yXXbNM

关于javascript - Jquery .each() 和 SetTimeout 随机时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44689381/

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