Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 280
fightstarr20 Avatar asked Nov 19 '25 01:11

fightstarr20


1 Answers

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);
like image 74
Koby Douek Avatar answered Nov 21 '25 14:11

Koby Douek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!