我看到许多使用 Node 的应用程序永远运行。
因此,我尝试使用 setInterval
方法,我认为它会让它永远运行,但显然它不会。
var request = require('request');
var queue = function(item) {
request({
uri: 'http://www.google.net'
},
function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Print the google web page.
}
})
};
setInterval(queue("google"),1000); //do this every 1 second.
当我运行上面的程序时,它会在一秒钟后停止。
如果我使用 node 运行它,如何修改上面的代码以使其保持运行?
最佳答案
实际上你的代码中有一个错误:
setInterval(queue("google"),1000);//每 1 秒执行一次。
您传递的不是上面的函数作为第一个参数,而是传递执行函数的结果。
所以,要么执行 setInterval(queue, 1000)
,要么执行以下操作(如果您需要多个参数):
setInterval(function() {
queue(how_many_params_you_want);
}, 1000);
关于javascript - 如何防止 Node 程序停止运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8501702/