How to limit the execution time of a function in javascript?
Asked Answered
S

2

13

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?

Skivvy answered 12/1, 2013 at 21:56 Comment(5)
Is there a reason you prefer trying to abort execution to simply avoiding infinite loops/recursion?Pitchman
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?Omdurman
The reason is that script execute user's code, not mySkivvy
«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 jsSkivvy
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.Omdurman
C
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.

Cancan answered 12/1, 2013 at 22:2 Comment(2)
Also Web Workers cannot access DOM elements. That may be a problem, especially since apparently, this is unknown code.Pitchman
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.Cancan
S
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
});
Sporades answered 12/1, 2013 at 22:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.