PEPEGA
PEPEGA

Reputation: 2281

Javascript performe action after animation end

I want to change the text after the animation is done but I have a hard time to find something that works. I have tried timers but that dont realy work beacuse the animation time is different every time (will add that later but now it is same every time).

  $(document).ready(function () {
        $("button").click(function () {
            var r = Math.floor(Math.random() * 2) + 1

            var moveTime;
            if (r == '1') {
                moveTime = 5000;
            } else if (r == '2') {
                moveTime = 4900;
            }
            var slowDown = 1000;
            var $div = $('div').css('left', 0);

            while (moveTime > 0) {
                slowDown--;
                $div.animate({
                    left: moveTime + "px"
                }, 3000);

                if (slowDown > 0) {
                    slowDown--;
                    moveTime = 0;
                }

                slowDown--;
                moveTime--;
            }

            document.getElementById("timer").innerHTML = r;


        });

    });
    div {
        position: absolute;
        float: left;
        margin: 200px 0 0 -8400px;
        width: 10000px;
        height: 125px;
        background: repeating-linear-gradient(90deg, #DF0000, #DF0000 125px, #000000 125px, #000000 250px)
    }
    
    h1 {
        text-align: center;
        margin: 130px 0 0 0;
        font-size: 90px;
    }
    
    body {
        overflow: hidden;
    }
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button>Start Animation</button>
    <div></div>
    <h1 id="timer">|</h1>

</body>

Upvotes: 0

Views: 78

Answers (2)

haim770
haim770

Reputation: 49095

You can use the promise() method to map your animations to an array of promises, then use Promise.all() to do something when all have resolved:

var promisesArr = [];

while (moveTime > 0) {
    // ...

    promisesArr.push($div.animate({
       left: moveTime + "px"
    }, 3000).promise());

    // ...
}

Promise.all(promisesArr).then(function() {
    var r = Math.floor(Math.random() * 2) + 1
    document.getElementById("timer").innerHTML = r;
});

See Fiddle

Upvotes: 1

softwarenewbie7331
softwarenewbie7331

Reputation: 967

see official api for animate

you should be able to just call $(elem).animate().animate() and the second animate will only start when the first ends...

additionally, animate function takes a 'easing' parameter, something like "easein" will probably do what you want without needing to keep track of time at all.

Upvotes: 0

Related Questions