Hone logo
Hone
Problems

JavaScript Sleep Function Implementation

Creating a function that pauses the execution of JavaScript code is a common requirement for controlling the flow of asynchronous operations, animations, or simulating delays. This challenge asks you to implement a sleep function that pauses execution for a specified duration.

Problem Description

Your task is to create a JavaScript function named sleep that accepts a single argument: ms (milliseconds). This function should return a Promise that resolves after the specified number of milliseconds have passed.

Key Requirements:

  • The sleep function must return a Promise.
  • The Promise should resolve without any specific value when the time delay is complete.
  • The function should handle ms values of 0 or greater.

Expected Behavior: When await sleep(ms) is called within an async function, the execution of the async function should pause for ms milliseconds before continuing.

Edge Cases:

  • What happens if ms is 0? The Promise should resolve immediately.
  • What happens if ms is a negative number? While not explicitly required to handle, consider how your implementation might behave or if you should throw an error (though for simplicity, immediate resolution for non-positive values is acceptable).

Examples

Example 1:

async function demonstrateSleep() {
  console.log("Starting...");
  await sleep(2000); // Pause for 2000 milliseconds (2 seconds)
  console.log("Finished after 2 seconds.");
}

demonstrateSleep();

Output:

Starting...
Finished after 2 seconds.

Explanation: The demonstrateSleep function logs "Starting...", then await sleep(2000) pauses execution for 2 seconds. After the delay, it logs "Finished after 2 seconds.".

Example 2:

async function quickSleep() {
  console.log("Immediate action...");
  await sleep(0); // Pause for 0 milliseconds
  console.log("Continuing immediately.");
}

quickSleep();

Output:

Immediate action...
Continuing immediately.

Explanation: The quickSleep function logs "Immediate action...", then await sleep(0) resolves instantly, allowing the next log "Continuing immediately." to execute without any noticeable delay.

Constraints

  • The sleep function must be implemented in JavaScript.
  • The ms argument will be a non-negative integer.
  • The solution should be efficient and avoid blocking the event loop unnecessarily (this is inherently handled by using Promises and setTimeout).

Notes

This problem is a fundamental building block for asynchronous programming in JavaScript. The core mechanism for implementing a delay in JavaScript that doesn't block the main thread is setTimeout. You'll need to wrap setTimeout within a Promise. Remember that async/await syntax works with Promises, making this sleep function incredibly useful.

Loading editor...
javascript