Delay code execution in Javascript using a Promise and Async/Await

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() {
   console.log(1);
   await sleep(1000);
   console.log(2);
}
count();  
  

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

Andy

Front-end Engineer & Designer based in Dublin currently working @IBM.
I write about: Javascript, HTML, CSS, React JS, React Native and UI/UX Design.

Add comment