【问题标题】:NodeJS Set TimeoutNodeJS设置超时
【发布时间】:2012-10-19 09:12:37
【问题描述】:

我正在使用 phidgets 库通过 nodejs 与物理设备进行交互。我已经将它们全部物理连接起来,我要做的就是确保我的开/关时间是准确的。

这将是问题所在,因为我什至无法通过控制台正确注销有关 setTimout 的内容。

基本上,我正在尝试执行以下操作:

for ( var i = 0; i < 4; i++ ) {
    setTimeout( function(i){
        console.log('Input: "' + i + '", Executed with timeout of ' + i*1000 + 'ms');
    }(i), i*1000 );
};

但我的控制台只是吐出以下内容,没有超时。它是即时的。

Input: "0", Executed with timeout of 0ms
Input: "1", Executed with timeout of 1000ms
Input: "2", Executed with timeout of 2000ms
Input: "3", Executed with timeout of 3000ms

这与我想要的相差甚远。

关于发生了什么的任何想法?

【问题讨论】:

    标签: javascript node.js timer dom-events settimeout


    【解决方案1】:

    由于(i),您正在 setTimeout 调用中运行该函数

    改成

    setTimeout( function(i){
                console.log('Input: "' + i + '", Executed with timeout of ' + i*1000 + 'ms');
            }, i*1000, i );
    

    这样,您将函数“指针”传递到带有参数i 的 setTimeout 设置中

    PS:时间值i*1000之后的所有参数都会作为参数传递给你的回调函数

    【讨论】:

    • 嘿 Rishi,非常感谢,它运行良好。我可以问一下在函数末尾添加(i)(作为范围)和在 setTimeout 函数中添加(i)之间关于执行顺序的区别是什么?我不太明白为什么它还不等。
    • 好吧,当你把 () 放在一个函数之后它会运行它(是的,即使是你刚刚定义的)所以会发生的是函数将在循环本身期间运行并且返回值将是传递给 setTimeout,在这种情况下为 undefined,因此它将在循环期间立即运行,而 undefined 将进入超时时间
    猜你喜欢
    • 1970-01-01
    • 2019-06-06
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    相关资源
    最近更新 更多