Reputation: 45
I am still rather new to Javascript and programming in general, so I am sure these issues can be explained quickly. Here is the code:
This code counts the time difference between now and 10 am, counting up to 864000000, at which point it should trigger a log to the console: It's 10 am
.
Why is it that when I console.log(mill2then)
, the value remains static?
And then, when I create a function dynamic, which should theoretically dynamically create the same value, I get a weird value. I would expect the value to be what mill2then is, around 663000000, but I get -20069965 and can't quite determine why.
var now = new Date();
var then = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0)
var mill2then = then - now;
if (mill2then < 0) {
mill2then += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function(){console.log("It's 10am!")}, mill2then);
console.log("Run \n")
console.log("Now's time: " + Date.parse(now))
console.log("The time then: " + Date.parse(then))
console.log("The time to get there:" + mill2then + "\n")
function dynamic(){return new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - new Date()};
var displayDynamic = setInterval(function(){console.log("Why am I not the same as mill2then?: " + dynamic())}, 3*1000)
var displayMill = function(){setInterval(function(){console.log("Here's what the value of mill2then is: " + mill2then)}, 3*1000)};
setTimeout(function(){displayMill()}, 1.5*1000);
Upvotes: 1
Views: 89
Reputation: 35680
If you run your code after 10am, this code returns a negative number:
var mill2then = then - now;
It's then adjusted with this logic:
if (mill2then < 0) {
mill2then += 86400000; // it's after 10am, try 10am tomorrow.
}
You don't have the same adjusting logic in the dynamic function, hence the negative number.
If you run your code before 10am, both will be positive, but only mill2then is static (as MarkM pointed out.)
Upvotes: 1
Reputation: 92481
mill2then
IS static. It doesn't change with each call. In the first line, the return value of new Date()
is assigned to var now
and stays the same—it's the date/time when you made that first call.
The function dynamic
, on the hand, calls for a new Date()
with each call. Every you you call it you'll get a different value.
Upvotes: 0
Reputation: 1420
console.log(var)
console.log prints the value that argument has in the moment you call it. Changing the value of var won't make console.log() be invoked again. You will want to do something like this:
setInterval(function(){
console.log(var)
},1)
this will print the value each millisecond, so if the value will change it will be printed changed the millisecond after.
When it comes dynamyc function, i am not sure, try adding some ( ) in your code or simply return the computed value.
function dynamic(){
var a = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - new Date();
return a};
Upvotes: 0