I found the jQuery animate()
behaves somewhat like a promise, because one task will finish first, before the second task is performed, very much like two chained promises.
The fact that setting the html of the div
can happen before the animation completion in the code below, also suggests that animate()
is like a promise -- it returns immediately and is non-blocking.
But I found that if I just call the animate()
twice on an element (#shape2
) with two different animations, they will run one after another, instead of having both animations of sliding-down and rounding-the-corner happen at the same time. In fact, it is just the usual jQuery chaining, not a promise chaining.
So is animate()
a promise or not?
(if it is a promise, shouldn't console.log($("#shape").animate().then)
print out something other than undefined
?)
As a side note, it looks like one possible implementation of it is just using setTimeout
or setInterval
, to perform a series of small animations for the first animate()
, and perhaps there is a currentAnimationID
being set to 1 or some random ID value, the second animate()
won't run at all, until the first animation finished and set the currentAnimationID
to 2
so that the second animation will begin.
Or maybe internally, the first and second animations are implemented as chained promises and they are just automatically chained together. If that's the case, this automatic chaining is not a usual promise behavior but maybe just what is needed for usual animation requirements.
$("#shape").animate({
top: 100
}, 1000).animate({
borderRadius: 30
}, 1000);
$("#shape2").animate({
top: 100
}, 1000);
$("#shape2").animate({
borderRadius: 30
}, 1000);
$("#shape").html("hello");
$("#shape2").html("world");
#shape, #shape2 {
background-color: #00BFFF;
width: 100px;
height: 100px;
top: 0px;
left: 50px;
position: relative;
border-radius: 0;
display: inline-block;
text-align: center;
line-height: 100px;
vertical-align: middle;
font-size:18px
}
#shape2 {
left: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="shape"></div>
<div id="shape2"></div>
The jsfiddle version is on https://jsfiddle.net/pnkrhxs8/15 For some reason, in the jsfiddle version the two squares slide down at the same time, but on the Stackoverflow version, the right square slide down a little bit slower than the left one.