HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Create a JavaScript promise that resolves after a given amount of time

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptafterthatamountresolvestimecreategivenpromise

Problem

Ever wanted to create an artificial pause in your JavaScript code? Did you incidentally need it to be a Promise instead of a simple setTimeout()? Well, you're in luck, because it's quite easy to create a promise that resolves after a given amount of time.
All you have to do is create a new promise using the Promise() constructor, and then use setTimeout() to call the promise's resolve function with the passed value after the specified delay.

Solution

const resolveAfter = (value, delay) =>
  new Promise(resolve => {
    setTimeout(() => resolve(value), delay);
  });

resolveAfter('Hello', 1000);
// Returns a promise that resolves to 'Hello' after 1s

Code Snippets

const resolveAfter = (value, delay) =>
  new Promise(resolve => {
    setTimeout(() => resolve(value), delay);
  });

resolveAfter('Hello', 1000);
// Returns a promise that resolves to 'Hello' after 1s

Context

From 30-seconds-of-code: resolve-promise-after-amount-of-time

Revisions (0)

No revisions yet.