DNB5brims
DNB5brims

Reputation: 30648

Is this possible to limit javascript function executing time?

I got a long javascript function, it may process a few second. But I would like to limit the javascript executing time, if it is longer than X second, whatever the executing result, the function will be killed. Is this possible to implement that in JS? Thanks.

Upvotes: 0

Views: 1314

Answers (2)

Daksh Gupta
Daksh Gupta

Reputation: 7814

JavaScript is a single threaded, so one need to use async mechanism to achieve what you're trying to do.

One way of doing this with a single promise with TimeOut. If timeout happens then you promise is Rejected and if not the Promise is resolved.

A Sample code may look something like

var PTest = function () {
    return new Promise(function (resolve, reject) {
    setTimeout(function() {
      reject();
    }, 2000)
    // Lines of Code
    resolve();
  });
}
var myfunc = PTest();
myfunc.then(function () {
     console.log("Promise Resolved");
}).catch(function () {
     console.log("Promise Rejected");
});

Upvotes: 0

VadimB
VadimB

Reputation: 5711

I used promises to achieve this. I just started 2 promises: first is my function to be executed wrapper in promise, second is timeout promise - when operation consider to be failed and use reject in it.

Using Promise.race I just wait what action is completed first. If second - reject occurs, if first - my code completes successfully.

Here is example:

var p1 = new Promise((resolve, reject) => { 
  setTimeout(resolve, 2000, "long_execution"); 
}); 

var p2 = new Promise((resolve, reject) => { 
  setTimeout(resolve, 500, "ok"); 
}); 

var p3 = new Promise((resolve, reject) => {
  setTimeout(reject, 1000, "reject");
});

Promise.race([p1, p3]).then(values => { 
  console.log(values);
}, reason => {
  console.log(reason)
});

Promise.race([p2, p3]).then(values => { 
  console.log(values);
}, reason => {
  console.log(reason)
});

Upvotes: 2

Related Questions