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.

ArcadeSmasher
  • 145
  • 1
  • 10
  • 9
    You mean `code()`? – VLAZ Mar 24 '22 at 20:44
  • 1
    Shouldn't it be `if (!statement)`?' – Barmar Mar 24 '22 at 20:45
  • 5
    Don't think of it as code. It's a function, so you call it with `()`. – Barmar Mar 24 '22 at 20:45
  • @Barmar Oh! yes. didn't catch that – ArcadeSmasher Mar 24 '22 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. – Amadan Mar 24 '22 at 20:47
  • @Barmar so like `(code)` or `code()` or `function(){code}`? sorry, I`m not a pro at JavaScript – ArcadeSmasher Mar 24 '22 at 20:49
  • Just `code()` like VLAZ said above – Barmar Mar 24 '22 at 20:50
  • To call a function in javascript use open and close parens after the function reference: `code()`. If the function takes args, they will be passed within these parens `code('hello', 'world')`. – Alexander Nied Mar 24 '22 at 20:50
  • @Amadan I don't think so because in the executeWhen function it repeatedly checks every 100 miliseconds – ArcadeSmasher Mar 24 '22 at 20:51
  • If you say `executeWhen(ready == true, ...)`, you will test whether `ready == true`, decide it is `false`, and pass `false` to `executeWhen`. It will then test every 100ms whether `false` is true or not, which I am pretty sure not what you want. You want to pass a predicate, and test the predicate by executing it (just like you execute the code, when the time comes). – Amadan Mar 24 '22 at 20:56

1 Answers1

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);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks. I'm not familiar with the `=>` syntax though, but thanks! – ArcadeSmasher Mar 24 '22 at 20:58
  • It's an arrow function: https://stackoverflow.com/questions/24900875/whats-the-meaning-of-an-arrow-formed-from-equals-greater-than-in-javas/24900924#24900924 – Barmar Mar 24 '22 at 20:59