Podcast Episode 9: Count Up

Season 2: One-Liner JavaScript Coding Challenge for Frontend Engineers

Silicon Wat
One-Liner Coding Challenge Podcast
10 min readDec 9, 2021

--

https://podcast.siliconwat.com

One-Liner Buddhist Quote of Week

Don’t compare yourself with others: people shine when it’s their time.
— Buddha

If you’re looking for A Complete Frontend Developer Course for Beginners, check out this textbook written by Thon Ly exclusively for Medium:

To help you achieve full mastery, all three web languages (HTML, CSS, and JavaScript) are taught together in parallel within a musical context in order to deepen your understanding of their interrelationships in a fun and memorable way!

Episode 8: Count Down

All Episodes

Transcript for Podcast Episode 9

ATTN Frontend Ninja Monks: Can you increment a number inside a HTML document using only one line of JavaScript code? Come sharpen your coding chops in this episode!

To submit your solution for the next Frontend Coding Challenge, simply go to my Scoreboard webapp, or just mention my hashtag #onelinerpodcast in your Twitter post. To ask for help from fellow coders or find a pair programmer, check out our Facebook Group for this podcast!

If you know a great one-liner Frontend Coding Challenge to recommend for my show, please use my link below to record your message. And if you can speak slowly and clearly, I may even feature your voice in my next episode! But if it’s more convenient for you, feel free to reply in the Comments section of YouTube, Medium, Codepen, or Spotify pertaining to this episode.

Intro

Every Friday, I send out a Frontend Coding Challenge that can be solved with just one line of JavaScript code. Each episode will have problems for both aspiring Junior and Senior developers. And if you’re the first to submit a correct solution using my hashtag, your username will be recorded in my Scoreboard webapp. Moreover, your winning streaks will be awarded and highlighted in my show. The following Friday, I go over the problems, solutions, and explanations. The topics I cover are modern vanilla JavaScript, CSS and HTML to help you master web development, as well as Data Structures and Algorithms to help you practice for technical interviews. If you want to become a Frontend Ninja Monk, come sharpen your coding chops!

Problem

Last week, this one-liner Frontend Challenge was presented:

In the HTML code, there is a span tag with an id attribute of countup and a text content with the number 0.

Level Easy:

In only one line of JavaScript code, increment the number in the text content. Your code should work for any default number in the text content.

Level Medium:

In only one line of JavaScript code, increment the number in the text content every 1 second.

Level Hard:

Finally, in only one line of JavaScript code, increment the number in the text content every 1 second. However, when the number reaches 10, STOP.

Winners

For level easy, the first person to submit a correct answer was a Twitter user with a handle of panhiatha0 on Wednesday at 12:48 pm PST.

For level medium, the first person to submit a correct answer was also panhiatha0 on Wednesday at 12:39 pm PST.

A Big Congrats on your 5th winning streak! 🎉

For level hard, the first person to submit a correct answer was a Twitter user with a handle of 3iitos on Wednesday at 12:45 pm PST.

Also a Big Congrats on your 5th winning streak! 🎉

If you’re listening, you both get a coupon for 90% off of my upcoming Frontend course at Udemy!

Please check out my Scoreboard webapp located at podcast.siliconwat.com for instructions on how to claim your prize.

To discuss my coding challenges with these winners or other listeners, come join our Facebook Group! The link is in the show notes. It’s also a great place to find a study partner or pair programmer!

Solution

For level easy, the solution is:

Let’s break this down in the order the JavaScript engine executes:

countup is the id of the span element. As such, it becomes a global variable that references the span element.

As a DOM element, we can set its text content by calling its textContent property.

The problem wants us to increment the number in the span tag which is currently 0.

Obviously, we can simply set the new text content to the number 1.

However, this is not the correct solution because it is a static solution.

What we need is a dynamic solution that is not hard-coded.

For example, if we go the HTML code and change the number in the span tag to 3.

We would expect to see the number 4.

However, our JavaScript code will still output the number 1.

How can we refactor our JavaScript code so that it correctly increments no matter what number we enter inside the span tag?

The key insight is to realize that we can get any number that is present inside the span tag by simply calling its textContent property.

This will return whatever is inside the span tag as a string.

Before we can add 1 to it, we need to convert that string into a number.

We can do this with the global JavaScript function called parseInt():

Now as a number, we can finally add 1 to it.

In effect, any number that we enter inside the span tag will correctly increment.

For level medium, the solution is:

Let’s also break this down in the order JavaScript executes it:

setInterval() is a special type of function called a facade because it doesn’t exist natively in JavaScript. Rather, setInterval() is an API that the browser provides to JavaScript.

For setInterval() to work, it requires two parameters. The first parameter is a function known as the callback. And the second parameter is the delay in milliseconds. When these two inputs are provided, setInterval() will execute the callback function repeatedly with the given delay.

In our case, we want the callback function to be:

Which is the code from level easy expressed as an arrow function. This way, it can be executed repeatedly.

And the delay we want is:

1000 milliseconds which is equal to 1 second.

We can reuse the code from level easy because when it is executed, it increments whatever number is currently inside the span tag.

By passing this code as a function to setInterval(), it will be executed at every 1 second.

In effect, the number in the span tag will count up every 1 second.

Finally, for level hard, the solution is:

Let’s also break this down in the order JavaScript executes it:

When we call the setInterval() function, it returns a special number. This number is the ID associated with this particular setInterval() function.

Here, we want to save this special ID. And we do this by assigning it to a const variable called intervalID.

Why do we want to save this special ID?

The problem tells us to stop the countup when the number reaches 10.

Having this special ID, we can easily stop the setInterval() function from executing simply by calling the clearInterval() function and passing it the intervalID variable .

To do all of this in only one line, we can simply refactor the callback function using a ternary operator:

This code says:

When the number in the span tag is equal to the string 10, execute the clearInterval() function. Otherwise, continue to increment the number.

In effect, when the number in the span tag reaches 10, the countup will stop.

At that point, the textContent will be blank because after the clearInterval() function executes, it returns undefined.

Again, the specified amount of delay in the setInterval() API is not the guaranteed time of execution. But rather, it is the minimum time of execution.

In order words, if we set the delay to 0 seconds, we cannot expect our callback function to executive immediately.

Why is that? What doesn’t it execute instantly even though there is no delay?

To answer this question, first we need a little primer about how the browser executes JavaScript code.

For each web page, the browser creates only one thread for executing JavaScript code.

This is like a road that has only one lane for driving.

Other languages might have multiple threads for executing their code.

However, a multi-lane road causes more collisions than a one-way street.

For this reason, the browser chooses single threading to avoid concurrency collisions in favor of a better user experience.

Like all things in life, there’s always a trade off. With only one thread for code execution, how can we execute long running tasks without blocking this main thread from executing other code?

To continue our analogy, on a one-way street, a slow-moving car will block the entire flow of traffic.

To solve this dilemma, the browser creates a special waiting line called the event queue where functions can wait in line for their turn.

Basically, the main thread consists of the call stack where functions are currently being executed. The browser also creates a special automation called the event loop that constantly checks this call stack to see if it is empty.

And when it is empty, the event queue will push out the next waiting function to the call stack to be executed.

In JavaScript, we call these waiting functions asynchronous code.

Now, we’re ready to understand exactly how the setInterval() API really works under the hood of the browser.

When we give the setInterval() API the callback function we want to execute with a specified delay, the browser waits for that amount of time to pass before executing it.

This amount of delay is guaranteed.

However, before the callback function can actually execute, it first needs to wait in the event queue for its turn. All this waiting around contributes to a lag.

Because there may be many asynchronous functions ahead of our callback function in the event queue and the call stack, the specified delay that we want cannot be guaranteed.

As you can now surmise, most likely, it will take a little longer than we want.

This begs the question: What if we needed an accurate setInterval() for exact timing purposes? Does the browser have such an API?

Unfortunately, it does not.

But, there are many clever workarounds. For your reference, I created one that takes advantage of the system time in the Codepen for this episode.

Please take some time to study it and try it out, because it will be needed to solve the challenge in the next episode.

References:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
  2. https://developer.mozilla.org/en-US/docs/Web/API/setInterval
  3. https://developer.mozilla.org/en-US/docs/Web/API/clearInterval
  4. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
  5. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
  6. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals

Show Notes

Thanks so much for tuning in! I hope you learned something new today! By the way, in the show notes, there are links to my CodePen with all the problems and all the solutions:

https://codepen.io/siliconwat/pen/WNXoLMg

As well as a YouTube recording of this episode:

And a transcript on Medium.

Remember to subscribe to my podcast and YouTube channel to be notified the instant I release the next episode!

Next Problem

For this week, your one-liner Frontend Challenge is this:

In the HTML code, there is a span tag with an id attribute of seconds and a text content with the number 0. There is also a button tag with an id attribute of stopwatch and a text content of Pause / Resume.

In the JavaScript code, the class SetExactInterval is being imported from the Codepen of the previous episode.

Level Medium:

In only one line of JavaScript code, use this SetExactInterval class to increment the number in the text content every 1 second.

Level Hard:

In only one line of JavaScript code, when the stopwatch button is clicked, PAUSE the seconds if it is currently running. Otherwise, RESUME the seconds if it is NOT currently running.

YOUR HINT: In your one-line solution for level medium, store the new object created by the SetExactInterval class to a variable called exactInterval.

Outro

To submit your answer to this challenge, simply include the hashtag #onelinerpodcast in your Twitter or Facebook post. Or, you can go to my Scoreboard webapp located at podcast.siliconwat.com.

If you’re the first person to submit a correct solution, I will give you a coupon for 90% off of my upcoming Frontend Course at Udemy.

Again, don’t forget to subscribe to my podcast and YouTube channel to be notified the instant I release the next problem.

Lastly, if you can think of a great one-liner Frontend Challenge to recommend for this show, please call in and leave a voice message! Thanks so much!

Episode 10: Season 3 Begins!

All Episodes

When you use my referral link above 👆 to become a Medium member, all proceeds will be donated towards the construction of the Silicon Wat Campus for children in Ukraine and Cambodia ❤️

--

--