Skip to main content

JavaScript: Sleep Function

We sometimes need a thing to delay the execution of the next function.

There is no built-in method to do that. But, it is possible by implementing both Promise and setTimeout.

In prior times, we only had setTimeout, or combined using setInterval. That worked. But now, we have Promise. So let's use it.


Create the Function

Let's name our function as sleep.

Or we can compact that using arrow expression, as such:

As you can see above (arrow expression), the function sleep is defined using const (constant) because a function usually stays like that for the entire lifecycle of the script, unless you do have some logic that dictates changes.


How to Use

Now, we can use it using await or then chain.

Let's assume everything in arrow expression.

This is the method to invoke sleep using await within async function.

This is the (direct) then chain invocation.

Since await cannot be used in global scope, the second method (using then) is the way to properly implement it.


So with this, we can now introduce the thing we sometimes need to delay the execution of the next function 👍

SLEEPING BREAD

Reference

  • Arrow function documentation at MDN.
  • Promise documentation at MDN.
Last modified on

Comments