How would I execute code not from a string? Here is an example:
var ready = false;
executeWhen(ready == true, function() {
console.log("hello");
});
function executeWhen(statement, code) {
if (statement) {
window.setTimeout(executeWhen(statement, code), 100);
} else {
/* execute 'code' here */
}
}
setTimeout(function(){ready = true}, 1000);
Could I use eval();
? I don't think so, I think that's only for strings.
CodePudding user response:
You call it with code()
.
You need to change statement
to a function as well, so it will get a different value each time you test it.
And when you call executeWhen()
in the setTimeout()
, you have to pass a function, not call it immediately, which causes infinite recursion.
var ready = false;
executeWhen(() => ready == true, () =>
console.log("hello"));
function executeWhen(statement, code) {
if (!statement()) {
window.setTimeout(() => executeWhen(statement, code), 100);
} else {
code();
}
}
setTimeout(function() {
ready = true
}, 1000);