0

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.

10
  • 9
    You mean code()? Commented Mar 24, 2022 at 20:44
  • 1
    Shouldn't it be if (!statement)?' Commented Mar 24, 2022 at 20:45
  • 5
    Don't think of it as code. It's a function, so you call it with (). Commented Mar 24, 2022 at 20:45
  • @Barmar Oh! yes. didn't catch that Commented Mar 24, 2022 at 20:47
  • 3
    Also, executeWhen(ready == true, ...) should be executeWhen(() => ready, ...) so that you can check it repeatedly, not just at the invocation time. Commented Mar 24, 2022 at 20:47

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I'm not familiar with the => syntax though, but thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.