JavaScript Sleep Function Workaround Tutorial

Last Updated on by in JavaScript
JavaScript Sleep function will be explored in this article. The sleep or delay function is infamous when it comes to all the languages where it exists. Some would argue that there has to have a callback or signal to fire a particular functionality.Others would argue that an arbitrary delay isn’t wholly a bad thing. I would say, to each his own. There are no hard and fast rules in this industry.

Let’s see more of Sleep JavaScript function below.

Well, there is nothing complicated about writing a sleep function. You can quickly write one with the help of JavaScript Promises:

function sleep(duration) {
  return new Promise((resolve) => setTimeout(resolve, duration));
// Usage
sleep(1000).then(() => {
    // Call function after the sleep()
    console.log('Sleep function is working!')

If there are no promises, then you need to rely on a callback method in JavaScript. All thanks to beautiful promises, we can resolve right after setTimeout. At this point, we can use ‘then’ to execute the next step. You need to keep in mind that the demo mentioned above uses ES6 arrow functions.

Digamber - Author

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.