halted
halted

Reputation: 15

End node.js process with a loop after 5 seconds

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)
}

Upvotes: 0

Views: 686

Answers (1)

jabaa
jabaa

Reputation: 6837

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.

Upvotes: 1

Related Questions