Exercise 2

Visit sleepyti.me and notice the calculate button which comes after "I plan to FALL ASLEEP at..." clause. Give it a try and understand the functionality. Then, try to reproduce it.

Solution

We need to make some changes to the content:

<p>I plan to fall sleep at...</p>

<select id="hh">
    <option>(hour)</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
    <option>10</option>
    <option>11</option>
    <option>12</option>
</select>

<select id="mm">
    <option>(minute)</option>
    <option>00</option>
    <option>05</option>
    <option>10</option>
    <option>15</option>
    <option>20</option>
    <option>25</option>
    <option>30</option>
    <option>35</option>
    <option>40</option>
    <option>45</option>
    <option>50</option>
    <option>55</option>
</select>

<select id="ampm">
    <option>PM</option>
    <option>AM</option>
</select>

<br>
<br>

<button onclick="handleOnClickEvent();">CALCULATE</button>

We further need to adjust the output content:

<div class="output">
    <p>If you fall sleep at the specified time above, you should try to wake up at one of the following times:</p>
    <p id="hours">11:44 PM or 1:14 AM or 2:44 AM or 4:14 AM or 5:44 AM or 7:14 AM</p>
    <p>A good night's sleep consists of 5-6 complete sleep cycles.</p>
</div>

Now, we must update our JavaScript code to base its sleep cycle calculation on the time specified by the user (using the drop-down lists). So, take out the following statement:

let now = Date.now();

and replace it with the following:

let hh = document.getElementById("hh").value;
let mm = document.getElementById("mm").value;
let ampm = document.getElementById("ampm").value;
hh = ampm === "PM" ? hh + 12 : hh;
let now = new Date();
now.setHours(hh);
now.setMinutes(mm);
now = now.valueOf(); 
  • The value property sets or returns the value of the selected option in a drop-down list.

  • The valueOf() method returns the primitive value of a Date object.

Finally, we must adjust our JavaScript code to not take into account the "14 minutes" to fall sleep since the assumption is that the user falls sleep at the specified time. So, comment out the following line:

now += 14 * minute;

There is a bug 🐛 in the solution provided here. We will revisit this in future lectures as an opportunity to work with the built-in debugger in Chrome/FireFox Developer Tools.