user1431314
user1431314

Reputation: 153

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

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?

Upvotes: 13

Views: 5672

Answers (2)

asgoth
asgoth

Reputation: 35829

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.

Upvotes: 6

Jamund Ferguson
Jamund Ferguson

Reputation: 17014

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
});

Upvotes: 1

Related Questions