我有一些每秒更新一次的计时器。我想在改变计时器变量时执行一些函数。如果有人能帮我。我提供了下面的代码:
for(var i=0; i<listingTime.length; i++){
if (listingTime[i].time >= 0) {
var second = listingTime[i].time / 1000;
var currentHour = parseInt(second / 3600);
}
}
这里,我想检测currentHour变量的变化
您可以在循环之前设置一个previous值变量,并且每当更新currentHour时,只需将其与previousValue变量匹配即可。如果它们相同,则不更改,如果它们不相同,则更改,并且可以执行回调。
另一种方法是使用对象原型来改变currentHour的值。下面的代码显示:
上面的代码可以修改如下,以添加一个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)
}
}
这个技巧可以在下面的代码中独立测试:
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>
这将执行changeListner
,如果有一个变化从以前的值。