11

There is a asynchronous function fun(param, callback) like this:

fun(param, function(err){
    if(err) console.log(err);
    doSomething();
});

How do I set a time limit to run this function?
For example, I set time limit equals to 10 secs.
If it finish in 10 seconds, there is no error.
If it run exceed 10 seconds, terminate it and show error.

1

3 Answers 3

16

Promises are ideal for this kind of behavior you could have something like:

new Promise(function(resolve, reject){
   asyncFn(param, function(err, result){
        if(error){
          return reject(error);
        }
        return resolve(result)
   });

    setTimeout(function(){reject('timeout')},10000)
}).then(doSomething);

this is using the basic ES6 Promise implementation. however if you want to include something like bluebird you can find more powerful tools like promisification of functions or entire modules and promise timeouts.

http://bluebirdjs.com/docs/api/timeout.html

this in my opinion would be the preferred approach. Hope this helps

Sign up to request clarification or add additional context in comments.

Comments

4

The easiest way to do this is to capture the function in a promise.

var Promise = require("bluebird");
var elt = new Promise((resolve, reject) => {
   fun(param, (err) => {
     if (err) reject(err);
     doSomething();
     resolve();
});

elt.timeout(1000).then(() => console.log('done'))
                 .catch(Promise.TimeoutError, (e) => console.log("timed out"))

Comments

2

I have made a module 'intelli-timer'

var timer = require('intelli-timer');

timer.countdown(10000, function(timerCallback){  // time limit is 10 second

    do_something_async(err, function(){
        timerCallback();    // timerCallback() after finish
    });

}, function(err){

    if(err) console.log(err);  // err is null when the task is completed in time
    else console.log('success');

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.