Umer Umer - 4 months ago 18
Node.js Question

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. But its not working.

while(1){

var ms=4000;
ms += new Date().getTime();
while (new Date() < ms){}

execute(12345,0);

}

Answer

In Javascript you can create some tasks to be called on every interval needed using setInterval:

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

Behold

setInterval timing is not accurate so you can't count on this for vital situations.