Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a time limit to run asynchronous function in node.js?

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.

like image 370
Larry Lu Avatar asked Apr 13 '16 03:04

Larry Lu


People also ask

How do I add a timeout to async?

In order to create the timeout, we will use an asynchronous function that takes in a Promise, as well as a time limit. Since JavaScript's native setTimeout function uses milliseconds as a parameter, we will use the same to keep things simple. const asyncCallWithTimeout = (asyncPromise, timeLimit) => {};

How do I add a delay in NodeJS?

One way to delay execution of a function in NodeJS is to use the seTimeout() function. Just put the code you want to delay in the callback.

Can I use setTimeout in NodeJS?

The setTimeout function is used to call a function after the specified number of milliseconds. The delay of the called function begins after the remaining statements in the script have finished executing. The setTimeout function is found in the Timers module of Node. js.


3 Answers

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

like image 179
Dayan Moreno Leon Avatar answered Oct 17 '22 07:10

Dayan Moreno Leon


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"))
like image 38
ŹV - Avatar answered Oct 17 '22 08:10

ŹV -


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

});
like image 35
Larry Lu Avatar answered Oct 17 '22 09:10

Larry Lu