setTimeout() repeatedly calling function while ignoring interval

Last time did a complete moron mistake , so double checked this time. Here is the code snippet:

var os = require('os');

var hostName = os.hostname();
var hostPlatform = os.platform();
var hostArch = os.arch();
var hostRelease = os.release();

function collectNow(){
    var hostInfo = {
        name : hostName,
        platform : hostPlatform,
        arch : hostArch,
        release : hostRelease,
        hostUptime : os.uptime(),
        hostTotalMem : os.totalmem(),
        hostFreeMem : os.freemem()
    };
    return hostInfo;
}


function monConnect(delay){
    console.log(JSON.stringify(collectNow()));
    console.log(delay); // printing output making sure it is 10000
    setTimeout(monConnect,delay);
}

monConnect(10000);

This code waits about 10 secs after 1st print , then keeps printing above json in infinite loop without waiting and value of delay is undefined.

delay isn't being passed when you call monConnect for the second time. You need:

setTimeout(function () { monConnect(delay); }, delay);

Note that for the purpose of running a function every delay milliseconds, you can use setInterval:

setInterval(fn, delay);

There is a subtle difference in that this may fail if fn takes more than delay milliseconds to run, but your function shouldn't take that long to run.

When you do

setTimeout(monConnect,delay);

monConnect will be invoked after delay milliseconds. But, since monConnect is not passed any value, it will have the delay as undefined (the default value).

To fix this, you can pass the actual arguments to the function passed to setTimeout, like this

setTimeout(monConnect, delay, delay);

Now, the second argument passed to setTimeout will be the actual time delay after which monConnect should be called. The third argument is the argument passed to monConnect when it is invoked after the timeout.

Just fix this one call:

setTimeout(monConnect(delay), delay);