简体   繁体   中英

nodejs how to call a function again when it finishes

Let's say I have a function,

function hello(){
  console.log('hello world');
}

Now I want to call this function again, as soon as it finishes. So I do something like this:

function hello(){
  console.log('hello world');
  hello();
}

However, doing this does not work as expected, because due to the asynchronous nature of nodejs, hello is called again before console.log('hello world'); finishes executing.

Is there a way to run the function hello repeatedly, but wait until it finishes before it runs for a second time?

Your problem isn't the asynchronous nature of JavaScript. Rather, it's that you have an infinite recursion and that quickly causes a RangeError: Maximum call stack size exceeded to protect you from consuming all of a machines memory with a giant stack of function calls.

You are not required to have a stopping condition. You can actually use the asynchronous nature of JavaScript to fix it:

 function hello(){ console.log('hello world'); setTimeout(hello, 0); } hello(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM