javascript - setTimeout() 在忽略间隔的情况下重复调用函数

标签 javascript node.js

上次犯了一个彻头彻尾的白痴错误,所以这次要仔细检查。这是代码片段:

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

此代码在第一次打印后等待大约 10 秒,然后在无限循环中继续在 json 上方打印而不等待,并且延迟值未定义。

最佳答案

当你做的时候

setTimeout(monConnect,delay);

monConnect 将在 delay 毫秒后调用。但是,由于未向 monConnect 传递任何值,它会将 delay 设置为 undefined(默认值)。

要解决此问题,您可以将实际参数传递给传递给 setTimeout 的函数, 像这样

setTimeout(monConnect, delay, delay);

现在,传递给 setTimeout 的第二个参数将是实际延迟时间,之后应调用 monConnect。第三个参数是在超时后调用时传递给 monConnect 的参数。

关于javascript - setTimeout() 在忽略间隔的情况下重复调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29314248/

相关文章:

javascript - 单击按钮以允许网页在两次单击之间进行处理

node.js - 获取 Node 中最近一次 git commit 的哈希

node.js - 匹配 Mongoose 中的两个不同字段,聚合?

javascript - 为什么有些 npm 包以 @ 开头?

javascript - Bootstrap 3 - 最大化窗口时导航对齐未正确显示

javascript - 每分钟向服务器请求一次 - 其他方式然后超时?

javascript - 将 DIV 包裹在 Anchor 标签或其他地方

javascript - "word-break: break-word"没有反射(reflect)在 html2canvas 创建的图像中

node.js - 以编程方式安装提供其版本的 NPM 包

javascript - Puppeteer 有时会抛出 "UnhandledPromiseRejectionWarning: TimeoutError: Navigation Timeout Exceeded"