I made a small test code using the jquery transit plugin for animations.
The purpose of the script is to have a photo of a tower make a flip 90 degrees toward the user, switch to another tower image, and flip another 90 degrees to lay flat on the screen. The issue is that after the first 90 degree flip, the image disappears entirely until the for loop has concluded before doing the final flip as the second image. I'm looking to have it flip continuously until the loop is finished.
I imagine this has something to do with closures and scope...
Javascript:
$(function() {
for (var i = 0; i < 10; i++) {
$('#test_flip')
.css('background-image', 'url("tower1.jpg")')
.transition({
rotateY: '90deg'
}, function() {
$('#test_flip')
.css('background-image', 'url("tower2.jpg")')
.transition({
rotateY: '180deg'
});
});
};
});
jsfiddle: http://jsfiddle.net/ce9b9aja/
The issue lies in the fact that the for loop calls
.transition
10 times consecutively. The calls arequeued
in the jQuery queue (which is done behind the scenes by transit.js), but they are not queued in the order you're expecting.Take the following example:
In this example, the first transition
x:40
will be executed instantly because there is no queue. Despite the fact that it is executed instantly, since it is an animation, it will be using some form ofsetTimeout
orsetInterval
and will not be completed in thetransition
method call. Consequently, thescale:0.5
transition will be called while thex:40
transition is still animating, which will put it in the queue it beforey:40
is put in the queue.Therefore, the queue order is
Similarly, your code is producing the following queue:
Thus your code's behavior. It rotates the image
90deg
first, then it does it 9 more times, which doesn't change anything visually (hence the "pause"). Then it changes the image and rotates it180deg
and does that 9 more times also.One solution could be to create a recursive function using the callback of the
.transition
function. An example is implemented below:Updated fiddle here: http://jsfiddle.net/ce9b9aja/1/
The code above exclusively uses callback functions to dictate the order of events. When the first transition is completed, the callback function will "queue" the next transition, which will be executed instantly since nothing else will be in the queue. And so on.