JavaScript30 - Day 29

By Camilla Krag Jensen naxoc |

Day 29 of #javascript30 creates a countdown timer in the browser.

setInterval()

This exercise has some clever use of setInterval(). Understanding timers is a little more tricky than it seems, so take a good look at the examples in the docs too.

Select with Element.name

This one is so cool! I did not know you could do that. If you have an element that has a name like an input element, a link anchor, or even an image, you can "select" it by it's name. The name is a property on the document and will give you the same as if you used a querySelector:

document.myFormElement;

Is the same as:

const myForm = document.querySelector('.form-class');

Pretty cool!

string.padStart()

It the exercise, the minutes in the timer are padded with zero using a small ternary if. That might be the tersest way to do it, but I just wanted to mention string.padStart(). It doesn't have great browser support yet, but I like functions like this. Just give it the length you are shooting for and what you want the string padded with. It needs to be called on a string, so I had to "cast" to string first like this:

const minutes = Math.floor(seconds / 60);
const remainderSecs = (seconds % 60).toString().padStart(2, '0');
const display = `${minutes}:${remainderSecs}`;
endTime.textContent = `Be back at ${hour}:${minutes}`;

Where Wes' solution is like this:

const end = new Date(timestamp);
const hour = end.getHours();
const adjustedHour = hour > 12 ? hour - 12 : hour;
const minutes = end.getMinutes();
endTime.textContent = `Be Back At ${adjustedHour}:${minutes < 10 ? '0' : ''}${minutes}`;

Both are perfectly readable, but I do like the pad functions. There is a padEnd() too.