Niklas
Niklas

Reputation: 13145

Call custom function for each object in array

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);
};

Upvotes: 0

Views: 98

Answers (3)

Stphane
Stphane

Reputation: 3456

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);
});

Upvotes: 1

Tom Bowers
Tom Bowers

Reputation: 5140

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/

Upvotes: 1

Anton
Anton

Reputation: 32581

use setTimeout

change.forEach(function (i) {
    setTimeout(function () {
        _anim(i);
    }, 500 * i);
});

Upvotes: 1

Related Questions