Javascript: How do constantly monitor variables value

Connor picture Connor · Jan 8, 2011 · Viewed 21.4k times · Source

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?

Answer

Mike Samuel picture Mike Samuel · Jan 8, 2011

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.