1

I have certain timers which are updating every second. I want to execute some function on change of timer variable. If anyone can help me out. I have provided the code below.

for(var i=0; i<listingTime.length; i++){
    if (listingTime[i].time >= 0) {
      var second = listingTime[i].time / 1000;
      var currentHour = parseInt(second / 3600);
    }
}

Here, I want to detect change of currentHour variable.

Vaidehi Hirani
  • 266
  • 3
  • 9

1 Answers1

3

You can set a previous value variable prior to the loop, and whenever updating the currentHour, just match it with previousValue variable. If they are same, they are not changes, if they are not same, it is changed and you can execute the callback.

One more other way is to use the object prototypes to changes the value of currentHour. Following code shows that:

Above code can be modified to following to add a changeListner

var HourListner = {
  currentHour: null,
  update:  function(newValue, callback){
    
    if(this.currentHour !== newValue){
      this.currentHour = newValue;
      callback(newValue);
    }
  }
}
timer = Object.create(HourListner);

var changeListner = function(value){ 
  //value is the new value of currentHour
  console.log(value)
}

for(var i=0; i<listingTime.length; i++){
    if (listingTime[i].time >= 0) {
      var second = listingTime[i].time / 1000;
      var currentHour = parseInt(second / 3600);
      timer.update(currentHour, changeListner)
    }
}

And the trick can be tested independently in following code:

var HourListner = {
  currentHour: null,
  update: function(newValue, callback) {

    if (this.currentHour !== newValue) {
      this.currentHour = newValue;
      callback(newValue);
    }
  }
}
timer = Object.create(HourListner);

var changeListner = function(value) {
  //value is the new value of currentHour
  console.log(value)
  $('body').append('<p>'+value+'</p>')
}
var interval = setInterval(function(){
  var t = new Date();
  timer.update(t.getMinutes(), changeListner)
}, 200)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

This will execute the changeListner if there is a change from previous value.

Pankaj
  • 954
  • 8
  • 15