wupto
wupto

Reputation: 57

Javascript - check for variable

here is a very nooby question for which answer I searched way too long while not finding anything. I'm not used to javascript but other programming languages so, how does it work if you want something to be constantly checked for?

Here my code:

var test = 0;

$( ".test_div" ).click(function() {
    test = 1;
});

Now if I want to check if the variable is 1, constantly, what do I do? I tried this but it didn't work:

if (test == 1) { }

Thanks!

Upvotes: 0

Views: 826

Answers (4)

Roy Miloh
Roy Miloh

Reputation: 3411

I'll take you a little bit back, do you really need to check it constantly? even if there are known specific events when it's value can be changed? I think it depends on your needs.

First of all, I would consider Pub/Sub or Observer patterns, they would be definitely more efficient and reliable than running a special interval each X milliseconds.

Upvotes: 0

atulmy
atulmy

Reputation: 1383

There are several ways you can check if the value has changed.

Using setInterval method:

    var test = 0; // initial value
    var checkInterval = 1000; // time in millisecond, 1000 = 1 second

    setInterval(function() {
        if(test !== 0) { // check if test is not equal to initial value
            console.log("Test value changed! New value: "+test);
        }
    }, checkInterval);

The above code will test the condition every 1 second.

Upvotes: 0

Cagatay Ulubay
Cagatay Ulubay

Reputation: 2559

You are searching for something do be done in an interval

Following could help you:

var test = 0;
var interval;

function check_test() {
    if( test == 1 ){
        clearInterval( interval );
        console.log( "Test is 1 now!" );
    }
}

interval = window.setInterval( check_test, 1000 );

The 1000 is in milliseconds, so 1000 ms = 1 second. This will call check_test() every 1sec.

You also could do window.setTimeout in a simmiliar way, but this will do it just one time. Than you could call it inside the function again and if you want to stop it, you just stop calling it.

Upvotes: 5

Jonathan Smith
Jonathan Smith

Reputation: 2599

If you are using Chrome or Opera, have a look at Javascript Object.observe()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe

If you need something less bleeding-edge, you would need to use a framework (such as Angular, although others are available) where you can set watches on variables.

Upvotes: 1

Related Questions