In JavaScript, I rewrite every function so that it can end as soon as possible. You want the browser back in control so it can make your DOM changes.
Every time I've wanted a sleep in the middle of my function, I refactored to use a setTimeout().
Edit
The infamous sleep, or delay, function within any language is much debated. Some will say that there should always be a signal or callback to fire a given functionality, others will argue that sometimes an arbitrary moment of delay is useful. I say that to each their own and one rule can never dictate anything in this industry.
Writing a sleep function is simple and made even more usable with JavaScript Promises:
// sleep time expects milliseconds
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
// Usage!
sleep(500).then(() => {
// Do something after the sleep!
});
If you are inside an async function you can do a proper await step with the above definition of sleep():
// Available inside async functions:
await sleep(500);
// Do something after the sleep…