Jquery.each () and SetTimeout for a random amount of time

In short, I know why setTimeout does not work inside the .each function, but the case I'm trying to get is a bit more complicated.

This time I have two loops, internal and external. Actions must be performed in this exact order, otherwise the result will not be correct, that is, each SetTimeout () should stop everything else. In addition, the latency for each function should be random.

// 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());
});
+4
source share
1 answer

. , , 0, , "" , , setTimeout , .

, , .inner-. $(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-". , Self-Executing, , setTimeout.

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

0

Source: https://habr.com/ru/post/1679855/


All Articles