Skip to content Skip to sidebar Skip to footer

Javascript: How Do Constantly Monitor Variables Value

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 eff

Solution 1:

This solution use deprecated APIs. Computed properties and proxies are a better alternative except on the oldest browsers. See K2Span's answer for an example of how to use those.

Object.watch:

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.

Solution 2:

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;

Solution 3:

Use setInterval:

var key = ''setInterval(function(){
  if(key == 'value'){
    dosomething();
  }
}, 1000);

Solution 4:

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.

functionsetValue(value) {
    myVariable = value;
    notifyWatchers();
}

Solution 5:

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.

functionValueWatcher(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 = newValueWatcher("chris");

wacthedName.onBeforeChange = function(currentVal, newVal) {
    alert("about to change from" + currentVal + " to " + newVal);
}

name.setValue("Connor");

Post a Comment for "Javascript: How Do Constantly Monitor Variables Value"