Home > database >  End node.js process with a loop after 5 seconds
End node.js process with a loop after 5 seconds

Time:11-22

I'm having some issues with ending a node process after an X amount of seconds.

I tried some things of this nature:

setTimeout(() => { process.exit(0) }, 5000)

I have tried passing 1 into .exit(). I tried .kill(), and .abort(). I can't seem to find a solution!
I'm running a loop that is initiated after setTimeout. The loop looks like this:

let ran = 0;
while(true) {
   ran  ;
   console.log(ran)
}

CodePudding user response:

One approach is to replace the loop with recursive setTimeout:

let ran = 0;
function f() {
   ran  ;
   console.log(ran)
   setTimeout(f, 0);
}
f();

setTimeout(() => { process.exit(0) }, 5000)

This allows process.exit(0) to be called between two iterations.

  • Related