Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to execute code not from string using function?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading