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.

Digamber

I am Digamber, a full-stack developer and fitness enthusiast. I crafted this site to bestow my coding experience and love to write on JavaScript, React, Angular, Vue, Laravel.