简体   繁体   中英

Detect change in timer variable using jQuery

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM