Warm tip: This article is reproduced from stackoverflow.com, please click
javascript

An expression in a function is not evaluating to true when it should. How can I fix this?

发布于 2020-03-27 10:32:18

I am making a function to wait until a condition is true, then execute a function. The expression inputted is a == 5. a starts equal to 0, and every time the function is executed it goes up by 1. when it is equal to five, the function still evaluates to false.

my .js file:

var _ = {
    waitUntil: function(duringExecution, expression, onCompletion) {
        test();
        function test(){
            console.log(a + ' ' + expression);
            if((expression) == true) {
                onCompletion();
            } else {
                duringExecution();
                setTimeout(test, 200);
            }
        }
    }
}

a = 0;
_.waitUntil(function() {
    a++;
}, a == 5, function() {
    console.log('yay');
});

My HTML file has nothing in it, except for the script tag.

<!DOCTYPE html>
<html>
    <head>
        <title>example lul</title>
    </head>
    <body>
        <script src='under.js'></script>
    </body>
</html>

Every time the function is run, it prints the value of a and the results of the expression. The console just prints:

1 false
2 false
3 false
4 false
5 false
6 false
7 false
...

It just goes forever. When a == 5, it should print a true and stop, but it doesn't.

Questioner
Daniel Reynolds
Viewed
44
Maheer Ali 2019-07-04 00:05

Whenever you write an expression its always evaluated to its value. For example when you pass a == 5 to function it return false and false is passed to the function.

You need to wrap a == 5 in a function. And call it when you want to check the condition.

var _ = {
    waitUntil: function(duringExecution, expression, onCompletion) {
        test();
        function test(){
            console.log(a + ' ' + expression());
            if(expression() == true) {
                onCompletion();
            } else {
                duringExecution();
                setTimeout(test, 500);
            }
        }
    }
}

a = 0;
_.waitUntil(function() {
    a++;
},function(){ 
    return a == 5
}, function() {
    console.log('yay');
});