Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 733
user1431314 Avatar asked Jan 12 '13 21:01

user1431314


People also ask

How do you limit the execution time of a function call?

import signal from contextlib import contextmanager class TimeoutException(Exception): pass @contextmanager def time_limit(seconds): def signal_handler(signum, frame): raise TimeoutException("Timed out!") signal. signal(signal. SIGALRM, signal_handler) signal. alarm(seconds) try: yield finally: signal.

How do I limit a JavaScript function to run only once?

var something = (function() { var executed = false; return function(value) { // if an argument is not present then if(arguments. length == 0) { if (! executed) { executed = true; //Do stuff here only once unless reset console.

How do you delay a JavaScript operation?

To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.


1 Answers

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.

like image 169
asgoth Avatar answered Oct 27 '22 05:10

asgoth