Skip to content

Instantly share code, notes, and snippets.

@dinigo
Last active May 18, 2017 17:22
Show Gist options
  • Save dinigo/ee81411cede03d85d9f36c2297beb256 to your computer and use it in GitHub Desktop.
Save dinigo/ee81411cede03d85d9f36c2297beb256 to your computer and use it in GitHub Desktop.
Very basic timeoutCheck based javascript data watcher
w = 2;
var watcher = new Watcher(
'utag.handler.iflag',
function(name, o, n, t){
console.log('name: ' + name + ' old: ' + o + ' new: ' + n);
if(n === 1){
clearTimeout(t);
console.log('exito');
}
},
3000,
function(name){
console.log('timeout para la variable: ' + name);
console.log('fracaso');
}
);
function Watcher(name, onChange, time, onTimeout){
var _self = this;
_self.watched = []
_self.add = function(name, onChange){
if(name){
var watch = {
name: name,
oldVal: _self.getVal(name),
timeout: 'undefined'
};
if(!onChange) watch.onChange = function(name, o, n, t){
console.log('name: ' + name + ' old: ' + o + ' new: ' + n);
clearTimeout(t);
}
if(onTimeout) watch.timeout = setTimeout(function(){onTimeout(name);}, time);
if(!watch.oldVal) console.error('variable sin definir: ' + name);
else _self.watched.push(watch);
}
else {
console.error('no se declaro nombre o onChange');
console.error(name);
console.error(onChange);
}
};
_self.remove = function(name){
_self.watched.forEach(function(v,i,a){
if(v.name === name){
var v = _self.watched.splice(i,1);
clearTimeout(v.timeout);
}
});
};
_self.getVal = function(name){
var path = name.split('.');
var last = window;
for(var i=0; i<path.length; i++){
last = last[path[i]];
if(!last) {
return null;
}
}
return last;
};
if(name){
_self.add(name, onChange);
}
setInterval(function(){
_self.watched.forEach(function(v,i,a){
var newVal = _self.getVal(v.name);
if(newVal != v.oldVal){
var oldVal = _self.watched[i].oldVal;
_self.watched[i].oldVal = newVal;
v.onChange(v.name, oldVal, newVal, v.timeout);
}
});
}, time);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment