Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible Javascript bug?

Here's the code sample:

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <script>
            i = 0
            while(i < 500)
            {
                date = new Date()
                console.log(i, ' ', date);
                date.setHours(5)
                i++  
            }

        </script>

    </head>
    <body>
    </body>
</html>

The firebug console eventually outputs the date set at 5 hours rather than the original, unaltered date. I've only tested this on Firefox 17.

like image 559
Mark Twine Avatar asked Jan 22 '26 20:01

Mark Twine


2 Answers

That would depend on the browser's implementation of console.log. As far as I know, browsers have an asynchronous console.log function which would also be the case for Chrome. Execution for asynchronous functions is only when the browser is not doing stuff.

while (i < 500) {
    date = new Date()
    console.log(i, ' ', date); //this set aside
    date.setHours(5); //this executed first instead
    i++;
}

To prove that console.log is the one to blame, I have this code which outputs the result into the DOM instead of using console.log and it shows it right.

i = 0
while (i < 500) {
    date = new Date()
    $('body').append('<div>'+i+':'+date+'</div>');
    date.setHours(5);
    i++;
}
like image 82
Joseph Avatar answered Jan 24 '26 11:01

Joseph


console.log is not asynchronous, it is simply dynamic. When you log the date object using the comma notation, you are logging a live reference to that date object, so when it updates, so does the console display. If you logged using toString instead, the value would not change :

console.log("logging date as string, i : " i + " date : " + date);
like image 43
Frances McMullin Avatar answered Jan 24 '26 10:01

Frances McMullin