views:

170

answers:

5

I'm trying to do a very basic date-difference calculation with javascript, but am getting mixed behavior from setInterval().

This updates constantly:

var init = setInterval(function(){
  document.getElementById("txt").innerHTML = new Date();
}, 1000);

But this only updates once:

var init = setInterval(function(){
  var today = new Date();
  var started = new Date(); started.setYear(1983);
  var difference = today - started;
  document.getElementById("txt").innerHTML = difference;
}, 1000);

I don't get it. If I can show the date every second, why can't I show the difference in dates every second?

+4  A: 

You're resetting today each time the function is called, so while the time changes, the difference between "today" and "today, 1983" is always the same.

Moving the assignment of today out of the interval, so it's only set once, worked for me. I see the number changing every second.

$(function () {
  today = new Date(); 
  var x = setInterval(function(){
    started = new Date(); started.setYear(1983);
    difference = today - started;
    document.getElementById("txt").innerHTML = difference;
  }, 1000); 
});
Patrick McElhaney
That's strange. Fixes the problem, but makes no sense :) Why would it matter if I constantly assigned date each time...
Jonathan Sampson
I expanded my explanation. Hopefully makes more sense now. :-)
Patrick McElhaney
@Jonathan - because the difference between A+B and A is always B, no matter what the value of A is.
annakata
Ah, I get it now. I had it stuck in my head that today was YYYY/MM/DD - silly of me :) Thanks for tolerating this juvenile mistake.
Jonathan Sampson
You were kind enough to tolerate my "int is a reserved word," so I guess we're even. ;-)
Patrick McElhaney
A: 

Actually it works as expected. Just wait till midnight.

Andrejs Cainikovs
+2  A: 

They both are executing once every 1000ms (1 per sec); however the second results in the same value every time, 820540800000. I assume you also realize that you can avoid polluting the global name space by judicious use of "var".

chuckj
A: 

I think you'll find it is actually updating constantly (easily seen by just putting an alert in the function), your problem is that the value is the same every time.

annakata
A: 

The problem is that you are not setting the started date fully, only the year. So you are updating that date's seconds minutes and hours every time the interval executes. To fix this you must set it to a specific year, month, day, hour, minute, second and millisecond.

This is partially working, if you sat there for a full year you would see the difference

Ori Cohen