Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

JavaScript - sleep function

0 contributions
3 points

In this short article, we're going to have a look at how in JavaScript create sleep(ms) function.

Quick solution:

  1. create new function called sleep,
  2. create inside and return Promise object,
  3. resolve Promise with setTimeout after indicated time,
  4. call the sleep function with await before inside other async function.

Code:

let sleep = (ms) => {
    return new Promise(resolve => setTimeout(resolve, ms));        
};

// await sleep(1000); // <------ calling inside async function

Node: async/await operators were introduced in ES8 (ES2017). Use Babel or TypeScript to provide this functionality in older browsers.

Explaination

There is no available sleep function in JavaScript, but is is possible to emulate sleeping with acync functions. The main idea is to postpone resolve function call with setTimeout wrapped in Promise object. Later that create logic can be placed inside own sleep function and called with await keyword inside async method only - it is main disadvantage/andvantage of the approach. Advantage becasue our logic will not freeze web browser like infinity loop does.

More complicated runnable example code below:

// ONLINE-RUNNER:browser;

let sleep = (ms) => {
    return new Promise(resolve => setTimeout(resolve, ms));        
};

// Usage example:

let action = async () => {
    console.log('[START]');
    for (let i = 0; i < 5; ++i) {
        await sleep(1000); // sleeps 1s each iteration
        console.log(i);
    }
    console.log('[STOP]');
};
action();

 

0 contributions

Suggested wiki articles:

Suggested findings

Let's do the work and have some fun
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way. ‚̧ ūüíĽ ūüôā
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    we will help you. ūüĎć ‚úĒ ūü¶Ą
Read more