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: Use the typeof operator If you want to check whether a variable has been initialized or defined (i.e. test whether a variable has been declared and assigned a value) you can use the typeof operator.
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.
Use setInterval:
var key = ''
setInterval(function(){
if(key == 'value'){
dosomething();
}
}, 1000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With