12

The situation is:

User writes some js-code and it should be runned on some data (locally).

But sometimes there are endless loops or recursive calls… That's why I need to limit the execution time of a function but not to edit the function itself (and even if so — should I insert checks after every sequence point? but what about recursive calls?)

Are there any other solutions for this strange problem? Maybe eval can give some parse tree of the code or something like that?

user1431314
  • 143
  • 2
  • 5
  • Is there a reason you prefer trying to abort execution to simply avoiding infinite loops/recursion? – Ben McCormick Jan 12 '13 at 21:59
  • When you say it runs on some data locally, do you mean on the user's machine, or locally on some server under your control. If the latter, is this running in something like Node.js environment? – DWright Jan 12 '13 at 22:00
  • The reason is that script execute user's code, not my – user1431314 Jan 12 '13 at 22:01
  • «When you say it runs on some data locally, do you mean on the user's machine, or locally on some server under your control. If the latter, is this running in something like Node.js environment?» I mean on the user's machine but in the browser and using js – user1431314 Jan 12 '13 at 22:02
  • Well, if the user writes some js that slows down the user's machine because it loops endlessly, isn't this the best outcome? I.e. it'll help the user realize they need to fix their code. – DWright Jan 12 '13 at 23:03

2 Answers2

6

A possible solution is using Web Workers. A web worker is started in a separate thread and can be terminated.

var worker = new Worker('my_task.js');
...
worker.terminate();

Downside is that not all browsers support Web Workers.

asgoth
  • 35,552
  • 12
  • 89
  • 98
  • 1
    Also Web Workers cannot access DOM elements. That may be a problem, especially since apparently, this is unknown code. – Ben McCormick Jan 12 '13 at 22:06
  • Note: As usual, background threads—including workers—cannot manipulate the DOM. If actions taken by the background thread need to result in changes to the DOM, they should post messages back to their creators to do that work. – asgoth Jan 12 '13 at 22:11
1

Is this in the browser or in node?

In the browser you can put your code in a 0-second setTimeout to free up the run loop (and unblock the browser temporarily)

setTimeout(function() {
   // your code here
}, 0)

node has something fancier that looks like this and is slightly better:

process.nextTick(function() {
   // frees up the run loop even faster
});
Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50