We’ll start by creating a simple function that takes one parameter which is the total time we want to delay execution for. The function will return a Promise which will be resolved after the timer finished.

const delay = time => new Promise(resolve => setTimeout(resolve,time));

That’s basically it! Here are a couple of javascript tips & tricks if you’re not familiar with the Javascript ES6 syntax.

Now you can use your function like this:

// You can call the function and use .then();  
delay(5000).then(() => console.log('Hello World'));

// You can also use async/await
async function counter() {
   await sleep(1000);

Here you can find more details about async/await in javascript.