JavaScript Sleep Function Workaround Tutorial

Last updated on: by Digamber
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.


I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.