Why does the following JavaScript function not print anything?

综合技术 Node.js Recipes (源链)

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

Problem courtesy of: Hoa

Solution

Aside from passing setTimeout
instead of timeout
(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…

(function() {
    var timeout = 1000;
    var count = 0;
    schedule(timeout, function doStuff() {
        console.log(++ count);
        schedule(timeout, doStuff).start(); // Invoke .start() each time
    }).start(); // Removed useless "timeout" argument
})();

I don’t know why someone would take this approach, as it seems overly complex.

I’m not even sure why they were passing timeout
to 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 the timeout
and callbackfunction
parameters, but the object returned is used once and discarded, at which point we call schedule
again, and pass it the same args.

It would seem more useful as a demonstration if schedule
just returned a function, and you retained a reference to that function. It would then only require the one call to schedule
to hold the values.

var schedule = function(timeout, callbackfunction) {
    return function() {
        setTimeout(callbackfunction, timeout)
    }
};

(function() {
    var count = 0;
    var fn;
    (fn = schedule(1000, function doStuff() { // 1. assign the function returned
        console.log(++ count);
        fn();  // 3. invoke the same function again
    }))();  // 2. invoke the returned function immediately
})();

Solution courtesy of: user1106925

Discussion

The ‘start’ function in the anonymous returned by the ‘schedule’ function has a typo – it should call “setTimeout” with the argument “timeout”, not “setTimeout”:

var schedule = function(timeout, callbackfunction) {
  return {
    start: function() {
      setTimeout(callbackfunction, timeout); // Fix the second arg.
    }
  }
};

Also, the “doStart()” function call never calls the anonymous “start()” function again, so the log statement would only execute once.

Discussion courtesy of: maerics

This recipe can be found in it’s original form on Stack Over Flow
.

您可能感兴趣的

怪异的JavaScript系列(二) 译者按:JavaScript有很多坑,经常一不小心就要写bug。 原文: What the f*ck JavaScript? 译者:Fundebug 为了保证可读性,本文采用意译而非直译。另外,本文版权归原作者所有,翻译仅用于学习。 JavaScript...
10 Best Javascript Lightbox Plugins 2017 Lightbox can provide users with quick, focused information without navigating to another screen. They can be helpful for things such as product de...
Which Array Function When? There's a lot of hullaballoo some days about "you should use reduce more" or "you don't need a filter, use a map", or "For? Why not forEach?" The tr...
Inferno v4 正式发布,JavaScript 用户界面库... Inferno v4 版本已发布,该版本对项目过程逻辑进行了重写,并新增了一些新特性: {Inferno.createPortal(vNode, DOM)} can be used to render vNode to external location in DOM ...
Having trouble understanding the scope and variabl... I am working on a hangman game using javascript only. It is for a class. I am a noob at javascript and DOM so please be kind. At this point, I just wa...
Node.js Recipes责编内容来自:Node.js Recipes (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » Why does the following JavaScript function not print anything?



专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录