sleep()



Prompt
Write a sleep function in JavaScript that pauses code execution for a given amount of milliseconds. This function should return a Promise. Demonstrate this function by delaying a console log message by 2 seconds.
JavaScript is a single-threaded, non-blocking language, which means it doesn't really have a built-in sleep function like some other languages do. However, there are ways to emulate the same behavior.
Playground
To create a sleep
function in JavaScript, think about incorporating a delay mechanism with the help of setTimeout
, wrapped inside a Promise.
This approach allows you to pause your code's execution for a specified amount of time. Start by defining a function that returns a new Promise.
Within this Promise, use setTimeout
to set up a timer that lasts for the duration you want your code to wait.
When this timer completes its countdown, ensure it triggers the resolve
function of the Promise. This setup essentially tells your code to "sleep" until the timer is up, after which it's ready to resume execution.
Solution
Concept Explanation ðŸ§
The sleep
function in JavaScript is a way to pause or delay the execution of the subsequent code for a specified amount of time.
Cricket Game Break: In a cricket match, there's a break after a certain number of overs, known as the 'drinks break'. This break is essential for players to rest, hydrate, and strategize for the game ahead. In your program, think of the sleep function as this 'drinks break'. The code runs for a certain time (overs), then takes a pause (drinks break), and then resumes.
Code Explanation 💻
When you call sleep(ms)
, it initiates a delay for ms
milliseconds. During this time, the Promise is in a pending state. After ms
milliseconds, setTimeout
executes its callback, calling resolve
, which resolves the Promise. This means any .then
chained to the sleep
function will now execute.
Common Pitfalls
- Promises: If someone is not familiar with JavaScript Promises, they might have trouble understanding how the sleep function works. Promises can be complex.
- Using async/await: If the user tries to use the sleep function with await but forgets to declare the function as async, they'll run into an error
- No built-in sleep function: Some programmers coming from other languages might expect JavaScript to have a built-in sleep or delay function, and could get stuck trying to find it in the documentation.