I’m surprised I can’t find a clear answer to this. So, in jQuery, you can do this:
$(someElements).fadeOut(1000);
$(someElements).remove();
Which, will start a fadeOut animation, but before it finishes executing in the 1 second duration, the elements are removed from the DOM. But how is this possible? I keep reading the JavaScript is single threaded (see also: Is JavaScript guaranteed to be single-threaded?). I know I can do either:
$(someElements).fadeOut(1000).promise().done(function() {
$(someElements).remove();
});
or even better:
$(someElements).fadeOut(1000, function() {
$(this).remove();
});
What I don’t understand is how JavaScript runs in a “single thread” but I’m able to use these jQuery functions that execute asynchronously and visibly see the DOM change in different places at the same time. How does it work? This question is not: “How do I fix this”.
jQuery animations (and pretty much all javascript-based animations) use timers to run their animations. The call to
.fadeOut()just STARTS the animation and it doesn’t complete until some time later when a series of timer operations are done.This is all still single-threaded.
.fadeOut()does the first step of the animation, it sets a timer for the next step and then the rest of your javascript (including the.remove()) runs until completion. When that javascript thread finishes and the time elapses for the timer, the timer fires and the next step of the animation happens. Finally when all steps of the animation have completed, jQuery calls the completion function for the animation. That is a callback that allows you to do something when the animation is done.That is how you fix this issue:
You use the animation completion function and only remove the item when the animation is done.