开发者

jQuery animation order without callbacks

I am trying to write a program to illustrate a programmatic solution of "Towers of Hanoi" puzzle, where the disks are represented by absolutely-positioned div-s of different size. To make a move I have a function like this:

function move(peg_from, peg_to)
{
开发者_如何学运维//check if the move is valid
//update the game state
//......
//get the div we are moving, calculate it's new position
//move:
the_div.animate({left: new_left, top: new_top}, 500);
}

Then a solution may look like this:

move(1, 3);
move(1, 2);
move(3, 2);
//... etc...

Or recursive, or whatever. In any case, I want to be able to 'eval' any code, defined in terms of move(x, y), not in terms of jQuery's animation or callback functions. The problem is, all animation happens at once, while it needs to be in the calls order. Is there a way to do that?

I have tried adding .delay() to the animations, maybe it could work, but I can't figure out the correct timeouts, anyway. setTimeout() doesn't have any visible effect. Googling reveals some advices of using animation callbacks, but I don't think they are applicable to my case.


The answer to A non-nested animation sequence in jQuery? matches your problem as well (with little modifications)..

You need to .queue() your animatios..

var q = $({});

function moveToQueue(eg_from, peg_to) {
    q.queue(function(next) {
        //check if the move is valid
        //update the game state
        //......
        //get the div we are moving, calculate it's new position
        //move:
        the_div.animate({left: new_left, top: new_top}, 500, next);
    });
}


// usage
moveToQueue(1, 3);
moveToQueue(1, 2);
moveToQueue(3, 2);

Update

And because i enjoyed it ..
here is a full working solution .. http://jsfiddle.net/gaby/nZ4MU/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜