0

What I want to do is animate a couple of objects in order of the id's in the change list. But it seems all _anim runs at the same time.

How can I run them in order?

$("#Sim2").click(function () {

   var change = [9,4];

   change.forEach(function (i) {
        _anim(i);
   });
});

var _anim = function (id) {
    $("#number"+id).animate({
         left: '50%',
    }, 500);
};

3 Answers 3

1

use setTimeout

change.forEach(function (i) {
    setTimeout(function () {
        _anim(i);
    }, 500 * i);
});
Sign up to request clarification or add additional context in comments.

Comments

1

The function _anim below is guaranteed to run all animations is order. It executes the next animation from the completion callback of the last. It also includes an optional callback function which is executed when all animations have finished.

Here is the code in action. http://jsfiddle.net/Hrkee/

$("#Sim2").click(function () {
    var change = [9,4];
    _anim(change, 0, { left: '50%' }, 500, function() { alert('all complete'); });
});


function _anim(aryKeys, index, properties, duration, callback) {
    $("#number" + aryKeys[index]).animate(properties, duration, function(){
        if(index + 1 <= aryKeys.length - 1){
            _anim(aryKeys, index + 1, properties, duration, callback);
        } else {
            if(callback)
                callback();
        }
    });
}

FYI, I stole the code from a blog post I wrote about loading async javascript synchronously. http://www.mobtowers.com/load-cross-domain-javascript-synchronously-using-jquery/

Comments

1

You can use a recursive function ..

Fiddle HERE

function processElements(aRRay, k) {
    if (aRRay[k]) {
        $('#number' + aRRay[k]).animate({
            left: '50%'
        }, 500, function () {
            processElements(aRRay, k + 1)
        });
    }
}

$("#Sim2").click(function (e) {
    var change = [1, 2, 3];
    processElements(change, 0);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.