I have taken the following example from “Hands-on Node”. It uses some reasonably advanced techniques. I have copied the code verbatim and have tried to debug a few times but cannot figure out why nothing gets printed to my console.
var schedule = function(timeout, callbackfunction) {
return {
start: function() {
setTimeout(callbackfunction, setTimeout)
}
}
};
(function() {
var timeout = 1000;
var count = 0;
schedule(timeout, function doStuff() {
console.log(++ count);
schedule(timeout, doStuff);
}).start(timeout);
})();
Aside from passing
setTimeoutinstead oftimeout(which will still allow it to run once), if this is meant to loop the timer, then there’s a flaw.The code never calls
.start()again after the first time. You’d need to do this…I don’t know why someone would take this approach, as it seems overly complex.
I’m not even sure why they were passing
timeoutto the inital.start(). That function doesn’t use any argument passed. I updated to remove it.If this was meant to teach about the benefit of closures, then this example really does little to do that.
Yes, the
.start()function does reference thetimeoutandcallbackfunctionparameters, but the object returned is used once and discarded, at which point we callscheduleagain, and pass it the same args.It would seem more useful as a demonstration if
schedulejust returned a function, and you retained a reference to that function. It would then only require the one call toscheduleto hold the values.