-1

i'm trying to create a new object as an attribute of a JSON for all positions of an array that contains JSON objects, but the problem is when run this, it always prints out the last and only the last object created inside for cycle. I can't figure this out... Can anybody explain me why this happens? Here is my code:

for(var i = 0; i < data.length; i++){

        var clock = new Clock((datesService.parseToClock(data[i].endsAt) / 1000), data[i].id)
        data[i].clock = clock
        data[i].interval = setInterval(function(){
          clock.decrement()
          console.log('ID: ' +clock.getAuction() + ' | ' + clock.getDays()+' d '+ clock.getHours()+' h ' + clock.getMinutes() + ' m ' + clock.getSeconds())
        }, 1000)

      }
function Clock(tempo, auction){
  this.auction = auction
  this.tempo   = tempo
  this.seconds = this.tempo % 60
  this.minutes = (this.tempo / 60) % 60
  this.hours   = ((this.tempo / 60) / 60) % 24
  this.days    = (((this.tempo / 60) / 60) / 24)
}

Clock.prototype.decrement = function(){
  this.tempo --
  this.seconds = Math.floor(this.tempo % 60)
  this.minutes = Math.floor((this.tempo / 60) % 60)
  this.hours   = Math.floor(((this.tempo / 60) / 60) % 24)
  this.days    = Math.floor((((this.tempo / 60) / 60) / 24))
};

Clock.prototype.getAuction = function(){
  return this.auction
};

Clock.prototype.getDays = function(){
  return this.days
};

Clock.prototype.getHours = function(){
  return this.hours
};

Clock.prototype.getMinutes = function(){
  return this.minutes
};

Clock.prototype.getSeconds = function(){
  return this.seconds;
};

Just can´t understand why... Thanks guys :)

Pointy
  • 405,095
  • 59
  • 585
  • 614
João R.
  • 17
  • 1
  • 3

2 Answers2

0

This'll be closed as a duplicate question soon. The key issue is that the variable "clock" at the top of your code is shared between all the interval timer handlers. JavaScript scope is always at the function level. The way around that is to use another function to build the interval timer handler.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

Yes.. It's because you are creating your 'clock' var in the loop, so it's reset each time, and when the loop finishes, 'clock' equals the last value it was set to. In your set interval function it refers the the global clock var, so each version of it will have the same (last) value.

When you create an anonymous function like the one in setInterval, it will not run in the context of your for loop, it runs in the global scope, hence the variable confusion.

You need to refer to the clock property of the object, not the clock variable which is not local to the function..

I may not be explaining this very well, but google "javascript anonymous functions" or "var that = this" as that is the most common way to solve this type of issue.

whiteatom
  • 1,456
  • 2
  • 14
  • 33