3

I want to run some JS code from a string, and I want to set a timeout for this code or stop eval in case of exceptions in eval.

my code:

function run_code() {
    let code = editor.getValue();
    eval.call(null, code);
}

and if I put some infinite loop in code, the browser freezes forever:

function run_code() {
    let code = "while (true) { console.log('Q'); }";
    eval.call(null, code);
}

Is there a way to call eval with a timeout, or kill the existing eval with JS? How should I properly call eval to be able to stop it if I want to?

Thank you!

Timur Nurlygayanov
  • 1,095
  • 2
  • 11
  • 24
  • 2
    Javascript is single-threaded, so in a tight loop like this there is no other process you can run to check.. One option is you could maybe put your eval in a webWorker. Found this that might help -> http://blog.namangoel.com/replacing-eval-with-a-web-worker – Keith Jun 10 '20 at 14:03
  • https://stackoverflow.com/q/14870602/1048572 https://stackoverflow.com/q/43948315/1048572 https://stackoverflow.com/a/36426903/1048572 https://stackoverflow.com/q/32131431/1048572 – Bergi Jun 10 '20 at 14:44
  • @Keith, Thank you! This works well for my case! – Timur Nurlygayanov Jun 11 '20 at 05:56

0 Answers0