Brian
Brian

Reputation: 13593

node.js pause for a few seconds

I want my node.js program to print foo every 30 seconds. So I write a code like this:

let count = 0

function foo () {
  console.log(`foo`)
  count += 1
  // do other things that takes about 20 seconds.
}

while (count < 10) {
  console.log(`inside while loop`)  // my screen keep printing `inside while loop` until "JavaScript heap out of memory" error
  setTimeout(foo, 30000)  // It looks like that `foo` is scheduled to be triggered after 30 seconds. Before it gets triggered, node.js program keeps doing other things.
}

This code doesn't do what I expected.

It looks like that foo is scheduled to be triggered after 30 seconds. Before it gets triggered, node.js program keeps doing other things.

How can I pause the program during the 30 seconds?

The program runs a few seconds, then it crashed due to JavaScript heap out of memory error.

The sleep module doesn't work. Because as it sleeps, foo stops doing things I need.

Upvotes: 1

Views: 3562

Answers (1)

RidgeA
RidgeA

Reputation: 1546

this is because of asynchronous nature of JavaScript

While loop makes a lot of iterations and register setTimeout callback. It's better to register setTimeout callback after each callback execution.

let counter = 0;
function foo() {
  console.log(`foo ${counter}`);
  counter ++;
  if (counter < 3) {
    setTimeout(foo, 1000);
  }
}
foo();

another option is to use setInterval and check, if you need to cancel next execution of callback.

Upvotes: 2

Related Questions