How do I constantly check a variables value. For example:
if(variable == 'value'){
dosomething();
}
This would work if I constantly looped it or something, but is there an efficient way of triggering that as soon as the variable is set to that value?
Watches for a property to be assigned a value and runs a function when that occurs.
Object.watch() for all browsers? talks about cross-browser ways to do Object.watch
on browsers that don't support it natively.
Object.defineProperty(Object.prototype, 'watch', {
value: function(prop, handler){
var setter = function(val){
return val = handler.call(this, val);
};
Object.defineProperty(this, prop, {
set: setter
});
}
});
How to use:
var obj = {};
obj.watch('prop', function(value){
console.log('wow!',value);
});
obj.prop = 3;
As @Pekka commented, you can have a timer constantly poll the variable. A better solution, if it's all your code that's changing the variable, is to not just set the variable directly, but rather have all setters call a function. The function could then set the variable and do any additional processing you need.
function setValue(value) {
myVariable = value;
notifyWatchers();
}
If you encapsulate your variable so that the value can only be set by calling a function, it gives you the opportunity to check the value.
function ValueWatcher(value) {
this.onBeforeSet = function(){}
this.onAfterSet = function(){}
this.setValue = function(newVal) {
this.onBeforeSet(value, newVal)
value = newVal;
this.onAfterSet(newVal)
}
this.getValue = function() {
return value;
}
}
var name = new ValueWatcher("chris");
wacthedName.onBeforeChange = function(currentVal, newVal) {
alert("about to change from" + currentVal + " to " + newVal);
}
name.setValue("Connor");
Use setInterval:
var key = ''
setInterval(function(){
if(key == 'value'){
dosomething();
}
}, 1000);
来源:https://stackoverflow.com/questions/4631896/javascript-how-do-constantly-monitor-variables-value