fightstarr20
fightstarr20

Reputation: 12608

Wait until variable equals

I am trying to check if a variable is equal to 1 using javascript...

myvalue = 1;

function check() {
    if (myvalue == 1) {
        return setTimeout(check, 1000);
    }

    alert("Value Is Set");
}

check();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I am planning on adding a delay to the setting of the variable but for now why is this simple version not working?

Upvotes: 3

Views: 7247

Answers (1)

Koby Douek
Koby Douek

Reputation: 16693

Using setTimeout(check, 1000); calls the function only once. That's not what you are looking for.

What you're looking for is setInterval which executes a function every n miliseconds.

Look at the below example which waits for the value to be 1, using setInterval, and then clearing the setInterval instance once it does.

Wait 4 seconds when running the snippet below:

// First - set the value to 0
myvalue = 0;

// This variable will hold the setInterval's instance, so we can clear it later on
var interval;

function check() {
    if (myvalue == 1) {
        alert("Value Is Set");

        // We don't need to interval the check function anymore,
        // clearInterval will stop its periodical execution.
        clearInterval(interval);
    }
}

// Create an instance of the check function interval
interval = setInterval(check, 1000);

// Update the value to 1 after 4 seconds
setTimeout(function() { myvalue = 1 }, 4000);

Upvotes: 1

Related Questions