Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 efficient way of triggering that as soon as the variable is set to that value?

like image 731
Connor Avatar asked Jan 08 '11 01:01

Connor


People also ask

How do you check if there is a value in a variable JavaScript?

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.


2 Answers

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.

like image 198
Mike Samuel Avatar answered Oct 27 '22 01:10

Mike Samuel


Use setInterval:

var key = ''
setInterval(function(){
  if(key == 'value'){
    dosomething();
  }
}, 1000);
like image 33
Chandu Avatar answered Oct 27 '22 00:10

Chandu