Question

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?

Was it helpful?

Solution

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); 
});    

OTHER TIPS

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".

Actually it works as expected. Just wait till midnight.

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top