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.
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++;
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With