【问题标题】:Run function/code after certain time with nodejs使用nodejs在一定时间后运行函数/代码
【发布时间】:2014-08-28 13:50:39
【问题描述】:

我正在寻找一种在 N 秒后在 nodejs 中运行一些代码的方法。

试过 setTimeout() 但它似乎完全阻止它直到时间结束但这不是我想要的,因为我的服务器仍在发送和接收事件。

有什么建议吗?

【问题讨论】:

  • setTimeout 不会阻止。提供代码并证明
  • 我唯一的猜测是你认为被阻塞的代码被放在了回调函数中,而它应该放在setTimeout 函数调用之后。您需要发布代码以便我们更好地查明问题。
  • 谢谢你是对的,正在使用 setInterval 更正(N * 1000)但传递 settimeout 一个以秒为单位的参数而不是 ms

标签: javascript node.js timer delay settimeout


【解决方案1】:

其实setTimeout是异步的,所以不会阻塞。

setTimeout(function(){
    // this code will only run when time has ellapsed
}, n * 1000);
// this code will not block, and will only run at the time

【讨论】:

    【解决方案2】:

    实际上 setTimeout() 完全符合您的要求,它不会阻塞并且会在未来某个时间执行给定的函数。

    但是,要理解 Node.js 中发生的事情可能会很棘手。我强烈建议投资学习如何使用 Promise API。一开始可能会让人感到困惑,但它为您提供了一个非常灵活的结​​构来控制异步事件。这是我在学习如何使用 Promise API 时编写的一个示例。你会看到它实际上使用了 setTimeout(),但是将它嵌入到了 Promise 中。希望这段代码是不言自明的,可以帮助您实现所需。

    /* 
     *  Try out javascript Promise code in Node.js
     *   
     */
    
    "use strict";
    
    function getRandomBoolean() {
        return Math.random() > 0.5;
    }
    
    function getRandomInt(max) {
      return Math.floor(Math.random() * Math.floor(max));
    }
    
    for (let i = 0; i < 5; i++) {
    
        // Create a promise, which will randomly succeed (and call resolve) or
        // fail (and call reject) after a random time interval
        let intervalMS = getRandomInt(5000);
        let promise = new Promise(function (resolve, reject) {
            setTimeout(() => {
                if (getRandomBoolean()) {
                    // Success - Call resolver function
                    resolve(i+" Hooray!");
                } else {
                    // Treat this as an error - Call reject function
                    reject(i+" Sorry!");
                }
            }, intervalMS);
        });
        // When the promise is complete, show the results
        promise.then(
                // The first function is the resolve function, to be called 
                // with a result param upon successful completion of async task
                result => console.log("Success: "+result), 
                // Next is reject function, to be called with an error parameter when something failed
                error => console.log("Failure: "+error) 
        );
        // Flow of execution falls through to here without blocking
        console.log ("Created promise "+i+", will complete in "+intervalMS+" ms");
    }
    

    如果你在 Node.js 中运行上面的例子(或者实际上它也应该在浏览器中运行,我只是没有在那里测试过)你会看到类似下面的输出:

    Created promise 0, will complete in 853 ms
    Created promise 1, will complete in 2388 ms
    Created promise 2, will complete in 2738 ms
    Created promise 3, will complete in 3053 ms
    Created promise 4, will complete in 652 ms
    Success: 4 Hooray!
    Failure: 0 Sorry!
    Failure: 1 Sorry!
    Success: 2 Hooray!
    Success: 3 Hooray!
    

    请注意,“Created promise...”输出首先出现,向您显示执行失败而没有阻塞。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 2019-03-18
      相关资源
      最近更新 更多