[英]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');
但是,这样做确实如预期,因为由于的的NodeJS异步性,不工作
hello
之前再次调用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? 有没有办法重复运行函数
hello
,但是要等到函数完成后才能再次运行?
Your problem isn't the asynchronous nature of JavaScript. 您的问题不是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. 而是,您具有无限递归,并迅速导致
RangeError: Maximum call stack size exceeded
以防止您消耗具有大量函数调用的所有计算机内存。
You are not required to have a stopping condition. 您不需要处于停止状态。 You can actually use the asynchronous nature of JavaScript to fix it:
实际上,您可以使用JavaScript的异步特性对其进行修复:
function hello(){ console.log('hello world'); setTimeout(hello, 0); } hello();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.