[英]How to add a while(1) loop in nodeJS
In NODEJS I want a function that will keep executing after every 5 seconds, and I used while(1) loop with a time out of 5 seconds. 在NODEJS中,我希望每5秒就会执行一次的函数,并且我使用了while(1)循环且时间超过5秒。 But its not working.
但是它不起作用。
while(1){
var ms=4000;
ms += new Date().getTime();
while (new Date() < ms){}
execute(12345,0);
}
In Javascript you can create some tasks to be called on every interval needed using setInterval
: 在Javascript中,您可以使用
setInterval
创建一些需要在每个间隔上调用的任务:
setInterval(functionToCallOnInterval, intervalInMilliSeconds); setInterval(functionToCallOnInterval,intervalInMilliSeconds);
setInterval(function() { console.log('called about every 5 seconds'); }, 5000); setInterval(myFunc, 6000); function myFunc() { console.log('called about every 6 seconds'); }
setInterval
timing is not accurate so you can't count on this for vital situations. setInterval
计时不准确,因此在重大情况下您不能指望这一点。
You should use setInterval instead of WHILE loop. 您应该使用setInterval而不是WHILE循环。
setInterval(function(){
console.log('test');
},5000);
This 5000 is time in ms!! 这5000是毫秒时间!
The problem with your code is, you are running a thread with infinite execution and thus it will freeze the browser. 代码的问题是,您正在执行无限执行的线程,因此它将冻结浏览器。 Instead if you will use setInterval() then a new thread will be run at regular intervals in which your function will be executed.
相反,如果您将使用setInterval(),那么将定期执行一个新线程,并在该间隔内执行您的函数。 Hope you got the concept well.
希望您能很好地理解这一概念。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.