Is there a way of stopping a function after a delay? Nodejs

Viewed 1187

Is it possible to abort a function after a delay? Something like:

function f() {
    //Do some process here
}

after(10000).stop(f)

Any idea about how to do that? Thank you.

3 Answers

Try cluster module like this

const cluster = require('cluster');

if (cluster.isMaster) {
    const fn = cluster.fork();
    setTimeout(_=>fn.process.kill(), 300);
} else {
    for(;;) {
       process.stdout.write('#');
    }
}

You could wrap your function inside a function that checks for the time.

function stopExecutingAfter(timeout, fn) {
  var stopifAfter = Date.now() + timeout
  return function() {
    if(Date.now() > stopIfAfter) return
    fn.apply(null, arguments)
  }
}

So we will have library killer.js

const cluster = require('cluster');

module.exports = (fn, delay) => {
    if (cluster.isMaster) {
        const fn = cluster.fork();
        setTimeout(_=>fn.process.kill(), delay);
    } else {
        fn();
    }
}

And example for using it

const killer = require('./killer');

function fn() {
    for(;;) process.stdout.write('#');
}

killer(fn, 100);
Related