setInterval () with variable times

0

I'm trying to synchronize an animation with the background music. For this I am using the setInterval () function of javascript.

What is the problem that I face is that this function has a fixed parameter (time).

I need to run the animation at 10 seconds, then at 18 seconds, then at 40 seconds, etc ...

This is what I have so far:

    <script>
    $(document).ready(function () {
        var cadaTiempo = 10000;

        setInterval(function () {
            try {
                $('#divCampo').ripples({
                    interactive: false,
                    resolution: 128,
                    perturbance: 0.1,
                });
            }
            catch (e) {
                $('.error').show().text(e);
            }

            var tiempoDestruct = 1800;

            tirarOla(tiempoDestruct);

        }, cadaTiempo);

    });

    function sleep(time) {
        return new Promise((resolve) => setTimeout(resolve, time));
    }

    function tirarOla(tiempo) {
        var $el = $('#divCampo');
        var x = $el.width()/2;
        var y = $el.height()/2;
        var dropRadius = 30;
        var strength = 0.05;

        $el.ripples('updateSize');

        $el.ripples('drop', x, y, dropRadius, strength);

        sleep(tiempo).then(() => {
            $el.ripples('destroy');
        });
    }
</script>

PD: Trade to use nested IF to change the value of the variable eachTime , controlling it with flags, but it did not work out. The animation continues to run every 10 seconds anyway.

if(flag == 1){
  cadaTiempo == 10000;
  flag++;
}else if(flag == 2){
  cadaTiempo == 18000; 
  flag++;
}
    
asked by Oren Diaz 27.10.2017 в 23:43
source

1 answer

1

I think a possible solution could be to use the setTimeout() in a recursive function, I'll give you an example of a recursive function to add to your logic:

var tiempo = 0;

function ejecutar(){
    setTimeout(function(){
        ejecutar();
    }, tiempo)

    tiempo += 1000;
    
    $("#mensaje").append('<p>Me ejecuté a los ' + tiempo + ' milisegundos</p>');
}

ejecutar();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="mensaje"></div>
    
answered by 28.10.2017 / 00:07
source