← 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');
});
2
1
Asked 5 years ago by Jam Risser

Answers

Correct Answer

function setTimeoutAsync(time) {
  return new Promise((resolve) => {
    setTimeout(resolve, time);
  });
}
3
Answered 5 years ago by Jam Risser