简体   繁体   中英

Javascript function continues before finishing while loop

I am stuck with this while loop, I want to iterate a short animation 3 times, then hide the div running the animation.

$(document).ready(function () {
var count = 3;
while (count > 0) {
    $('img.arrow').animate({
        width: '+=25', height: '+=25', left: '-=15', top: '-=10'
    });
    $('img.arrow').animate({
        width: '-=25', height: '-=25', left: '+=15', top: '+=10'
    });
    count = count - 1;
}
if (count == 0) {
    hideDiv();
}
});

function hideDiv() {
$('.arrow_container').hide("slow");
};

If I remove the hideDiv(); call, the animation works as intended(3 iterations), but if I add it, the Div is hidden after about half of the first "animate" call

How come the if-statement checking the count == 0 does not stop it from calling the hideDiv method? Am I missing something?

The animate call only triggers the animation, it does not wait until the animation is actually done. Therefore your loop runs through in no time and then count is 0 and div is hidden.

You'll have to use callback functions to learn when animation is complete.

See documentation: https://api.jquery.com/animate/

The css animations are being triggered, but they take time. The JS is not waiting for the animation to finish, just firing the animate command, iterating, firing the command, iterating, and so on. The 'if' condition is true before the css animations are done.

One solution would be to use css to set the final attributes, not jQuery. Like: 0-99% is your animation, 100% is display: none.

Thank you for the replies, I chose just to set animation times and delay the function

Could there be drawbacks to this?

$(document).ready(function () {
var count = 3;
while (count > 0) {
    $('img.arrow').animate({
        width: '+=25', height: '+=25', left: '-=15', top: '-=10'
    }, 300);
    $('img.arrow').animate({
        width: '-=25', height: '-=25', left: '+=15', top: '+=10'
    }, 300);
    
    count = count - 1;
    setTimeout(() => { hideDiv(); }, 1800);
}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM