Image for post

On a recent technical interview I had for a big tech company, in one of the steps of the process I was asked the following:

Create a countdown from 1:30 to zero using plain javascript and HTML, and that’s all.

“Cool”, I said to myself, that’s something I can achieve easily. The total time I had to develop that was 45 minutes, which at first looked more than enough.

I started doing the simplest thing I could imagine, mimicking what a normal clock or countdown does: at each 1-second interval, we would decrease the value of the counter by 1 until the end of the 90-second period. This was the result:

const initialSeconds = 90;

let remainingSeconds;
/**
* Returns seconds in format mm:ss
* @param {Number} seconds
* @return {string}
*/
const formatMinutesSeconds = (seconds) => {
    const thisDate = new Date(seconds * 1000);
    return `${thisDate.getMinutes()}:${thisDate.getSeconds()}`;
};
/**
* Renders the remaining time in a format mm:ss
* @param {Number} seconds
*/
const renderCountdown = seconds => {
    const counterElement = document.getElementById('counter');
    const stringCounter = formatMinutesSeconds(seconds);
    counterElement.innerText = stringCounter;
};
/**
* Starts a countdown with the given seconds
* @param {Number} seconds
*/
const startCountdown = (seconds) => {
    remainingSeconds = seconds;
    setInterval(_ => {
        if (remainingSeconds > 0) {
            remainingSeconds--;
            renderCountdown(remainingSeconds);
        }
    }, 1000);
    renderCountdown(remainingSeconds);
};
startCountdown(initialSeconds);

As you can see, I used the native setInterval function to mimic a tick on a regular clock, and decreased the total amount of seconds by 1. By that time, around 10–15 minutes had passed and the interviewer told me:

Well done, but do you think it will be precise enough?

As you may know (or not), Javascript works with a single thread with no context switching, which in other words, means that functions are executed from the beginning until the end without interruptions, so, if there was another function somewhere taking a lot of time (let’s say a long for statement), it would cause some delays. Using a setInterval, will only guarantee that the callback function will be executed at least n seconds after the time is created, but if the Event Loop is busy at the moment of its completion, it will wait until it finishes all the previous tasks before running the code we want.

#js #vanilla-javascript #vanillajs #javascript-interview #javascript #programming

Creating a precise countdown with Vanilla JS
4.35 GEEK