Reputation: 13866
I'm facing the following code in a success block of an Ajax request:
$('#something').remove();
alert('something was removed');
When executed I expected it to finish removing 'something' and pop up an alert afterwards, but for some reason alert pops up and only after it's confirmed the element is removed.
Why does this happen? It's trivial code and I would like to avoid callbacks and such. What should I check?
It was tested on FF. Thanks for tips.
Upvotes: 1
Views: 1238
Reputation: 1442
As T.J. Crowder said in his answer:
DOM manipulations (inserting elements, removing them, moving them) are synchronous, although the user may not see the result until your JavaScript code completes, letting the browser use the thread to repaint the display.
Upvotes: 7
Reputation: 72271
Just like Ivan Minakov said in his answer, in order to see the page repainted before the alert, you have to let your JavaScript code complete. After this happens, you can schedule the continuation - displaying the alert.
Normally this doesn't happen in JavaScript - functions like alert and prompt are exceptional in the sense that they actually block the thread until the user acts.
This means that you can achieve what you want by:
$('#something').remove();
setTimeout(() => {
alert('something was removed');
});
or with async/await if that's your thing:
// in an async function
$('#something').remove();
await delay(0);
alert('something was removed');
// ...somewhere...
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Upvotes: 3