Sampson
Sampson

Reputation: 268364

Strange behavior from setInterval()

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?

Upvotes: 1

Views: 666

Answers (5)

Ori
Ori

Reputation: 5081

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

Upvotes: 0

annakata
annakata

Reputation: 75844

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.

Upvotes: 0

chuckj
chuckj

Reputation: 29545

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

Upvotes: 2

Andrejs Cainikovs
Andrejs Cainikovs

Reputation: 28454

Actually it works as expected. Just wait till midnight.

Upvotes: 0

Patrick McElhaney
Patrick McElhaney

Reputation: 59271

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

Upvotes: 4

Related Questions