Random addClass

0

I have this code which adds a class randomly every millisecond to a random div. But it is a very slow process. Is there any way to randomly add the classes to several divs at the time, say 10 at a time and not one at a time?

$(document).ready(function () {
    var $divs = $("circle");
    var classes = ["animated fadeInRight", "animated fadeInLeft", "animated fadeInDown","animated fadeInUp","animated zoomInRight","animated zoomInLeft","animated zoomInDown","animated zoomInUp"];
    var interval = setInterval(function () {
        var $ds = $divs.not(".animated .fadeInLeft");
        $ds.eq(Math.floor(Math.random() * $ds.length)).addClass(classes[~~(Math.random()*classes.length)]);
        if ($ds.length == 1) {
            clearInterval(interval);
        }
    }, 1);
});
    
asked by Maco Acero 30.01.2017 в 19:10
source

1 answer

0

To begin with, it must be borne in mind that generating random numbers can be a slow process. I propose the following code:

$(document).ready(function () {
    var divs = $("circle");
    var cantidadPorCiclo = 10; // Cantidad de divs que seran modificados por cada interval
    var classes = ["animated fadeInRight", "animated fadeInLeft", "animated fadeInDown","animated fadeInUp","animated zoomInRight","animated zoomInLeft","animated zoomInDown","animated zoomInUp"];
    var ds = divs.not(".animated .fadeInLeft");
    var cantidadTotal = ds.length; // Obtengo la cantidad de divs que no estan animados
    var interval = setInterval(function () {
        if (cantidadTotal == 0) // Si ya hice todos los cambios
            clearInterval(interval);
        var maximo = (cantidadTotal > cantidadPorCiclo) ? cantidadPorCiclo : cantidadTotal; // Modifico de a 10, y en caso de que no haya tanto modifico menos
        for (var i = 0; i < maximo && cantidadTotal > 0; i++) {
            ds.eq(Math.floor(Math.random() * ds.length)).addClass(classes[Math.floor(Math.random() * classes.length)]);
            cantidadTotal--;
        }
    }, 200); // Lo hace cada 200 milisegundos para poder darle tiempo a que haga el calculo. Sigue siendo muy poco tiempo (2/10 de un segundo)
});

In this way 10 items are set for each interval.

Note:

If you set it with 1 ms, the function is executed continuously without having finished, opening many processes in so little time that it generates saturation of the memory.

I hope it helps you. Greetings!

    
answered by 31.01.2017 в 14:53