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.
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');
});
Thank you! This solves my problem, but it would be nice if you didn't have to. Is there any way to have _.waitUntil turn a == 5 into a function or not? (I don't know what I'm really talking about so please let me know if i'm wrong.)
@MarkC.That is strange. for me it seems to work fine.
@MarkC. Sorry Its fixed now. I was missing
return
@DanielReynolds You will need to wrap
a == 5
in a function. If you want to passa == 5
only and change it to function dynamically inside_.waitUntil
then its not possible.@MarkC. ok. Thanks!