Coding ยท ยท

Sleepy

Problem to solve

I like to sleep. A lot. Please let me sleep as long as I want.

Specifically, I'm a command line program who's sole job is to sleep on demand.

In a file called sleepy.js in a folder called sleepy, implement a program in JavaScript that prompts the user for how many seconds to sleep for, then does that sleep, then asks them again, etc.

The user should be able to choose to sleep for an integer number of seconds between 1 and 10 seconds inclusive.

On receiving a valid input from the user, immediately show the message eg "About to sleep for x seconds".

After every second of the sleep (including the last second) show the message "Asleep for n seconds".

After the sleep is complete, show the message 'Awake!' then ask the user for how long they want to sleep for again.

Here's an example interactive session with a working program:

How many seconds would you like to sleep for? 99
How many seconds would you like to sleep for? 4
About to sleep for 4 seconds
Asleep for 1 seconds
Asleep for 2 seconds
Asleep for 3 seconds
Asleep for 4 seconds
Awake!
How many seconds would you like to sleep for? 2
About to sleep for 2 seconds
Asleep for 1 seconds
Asleep for 2 seconds
Awake!
How many seconds would you like to sleep for?

How to begin

In a terminal, create the folder with mkdir ~/code/sleepy and move into it with cd ~/code/sleepy. Start editing a new JavaScript file with code sleepy.js.

When you're ready to try out your program, run it with bun sleepy.js.

Stuck?

Look back over the lesson guide, in particular how to use setTimeout(), setInterval() and how to create and use await sleep(). Probably the most easy to reason about solution uses await sleep() (if you just copy-and-paste the function into your code and don't try too hard to understand how it works with 'promises' etc!), though solutions using setTimeout() and setInterval() are also very possible and help build your understanding of the JavaScript event loop. At the end of the lesson you'll be shown 2 different solutions to learn from.

If using setInterval() or setTimeout() you may also want to cancel a queued up interval or timeout - for usage, search the web for 'MDN clear timeout', for example. You should also think carefully about the scope of your variables, and make sure you're let'ing them in the correct places.

How to submit

Ask your teacher to check your code.