'Is there any way to await animation completion in Javascript

This is probably a long shot, however I need to fix this somehow, if you have any other tips that could help me achieve the same end result please let me know!

I have a with a bunch of items with unique IDs. These items are continously updated through a Cefsharp application (every 1000ms). I currently have a class named "show" that transitions the list item from 0 height to a specified height in 1 second. The same goes for when the item is removed (show is removed from classes). So everything here works as intended.

For some reason however, every now and then, my list animation seemed to cancel abruptly. I couldn't figure out why. Just a few minutes ago I realized it was my sortList function:

function sortList() {
    $("#orderQueueList li").sort(function (a, b) {
        return parseInt($(a).data('indexn')) - parseInt($(b).data('indexn'));
    }).appendTo('#orderQueueList');
}

This function is executed everytime a new item is added to the list or a current item has it's "indexn" value updated. So if the animation is queued (the animation has a 5 second setTimeout) and the list is sorted during this time, or during the actual animation, it is cancelled.

I haven't really been able to figure out how to solve this. My initial thought was that the sortList would wait until all animations are completed. However the animations are .CSS sided so I'm not sure if this is possible. I've been Googling around a bit and can't really find an answer.

I either want the 5 second delay to execute immediately (so the animation is completed) or the sortList function to wait until the animation is complete. Is this possible somehow through JavaScript/jQuery?

Thank you!



Solution 1:[1]

You can add another parameter to the animate function that triggers a function once it has finished jquery doc explaining that here (5000) is the duration) Note that the function is called once per matched elements

$( "#clickme" ).click(() => {
    $( "#whatever" ).animate({
        left: "+=50",
    }, 5000, () => { // <--- other parameter is here
        // Animation complete.
    });
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gui