Javascript code challenge by Dropbox Team

I’ve found the below code challenge in the Dropbox’s Web Engineer Job post. Thanks to HN.
It was not that difficult, here is my solution to the first code challenge (Javascript) with complete explanation.

Question:
Given the following javascript code:

function countdown (num) {
        for (var i = 0; i <= num; i += 1) {
            setTimeout(function () {
                alert(num - i);
            }, i * 1000);
        }
    }

    countdown(5);

The desired result is a countdown from 5 to 0 using alert messages. Explain why the code only alerts -1, then fix the code so it works as expected.

Answer:
Let's debug the code:
Debugging:

function countdown (num) {
    for (var i = 0; i <= num; i += 1) {
            setTimeout(function () {
                console.log("\nnum = " + num);
                console.log("\ni = " + i);
                alert(num - i);
                
            }, i * 1000);
        }
    }

countdown(5);

Output:
num = 5
i = 6
num = 5
i = 6
num = 5
i = 6
num = 5
i = 6
num = 5
i = 6


Hence, the code in question always alerts '-1'.

My fix for the above problem is:

function countdown (num) {
        for (var i = 0; i <= num; i += 1) {
            setTimeout(function () {
                if(i > num){
                    i = 0;
                }else{
                    i += 1;
                }
                alert(num - i);
                
            }, i * 1000);
        }
    }

countdown(5);

Explanation:
The alert box gives -1 every time (6 times), because the in-line function which has the alert() statement gets executed only after the loop is completed. By the time the loop is completely executed the value of 'i' will be 6. The program continues to execute and loop until the i<=num condition is satisfied. The in-line function which has alert() statement gets executed only after the specified time (i*1000) (that is, 0, 1000, 2000, 3000, 4000, 5000 in milliseconds) for six times with 1 sec delay for each alert box. So, The execution of loop gets'll be executed already before the first trigger of setTimeout().

So, the code is modified to reset the 'i' value to 0 when it is '6' and then keep increasing the 'i' value before alert() statement.

It was fun! :D

Note:
Note that, most of the browsers have a minimum delay set for setTimeout() call. Such as, 4ms to 10ms of minimum delay is set (depending on the browser) even though the timeout value (second parameter) is mentioned as '0' (zero). Check this out for more details - https://developer.mozilla.org/en/DOM/window.setTimeout

About these ads
This entry was posted in code, coding, debug, javascript and tagged , , , , , , . Bookmark the permalink.

One Response to Javascript code challenge by Dropbox Team

Comments are closed.