← JavaScript Interview Questions

JavaScript Promises

NodeJS has a `setTimeout(callback, time)` function that takes a callback for its first parameter and time in milliseconds for its second parameter. Below is an example of how this function is used.

setTimeout(() => {
  console.log('waited 5 seconds');
}, 5000);

Convert `setTimeout(callback, time)` into the promise `setTimeoutAsync(time)` so that it can be used the following way.

setTimeoutAsync(5000).then(() => {
  console.log('waited 5 seconds');
Asked a year ago by Jam Risser


Correct Answer

function setTimeoutAsync(time) {
  return new Promise((resolve) => {
    setTimeout(resolve, time);
Answered a year ago by Jam Risser