javascript nodejs中的setInterval
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26902094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
setInterval in nodejs
提问by user134414214
I am making an http request which should run after every one minute. Below is my code
我正在发出一个 http 请求,它应该每一分钟运行一次。下面是我的代码
var express = require("express");
var app = express();
var recursive = function () {
app.get('/', function (req, res) {
console.log(req);
//Some other function call in callabck
res.send('hello world');
});
app.listen(8000);
setTimeout(recursive, 100000);
}
recursive();
According to the above code, I must get response after every one minute. But I am getting Error: listen EADDRINUSE. Any help on this will be really helpful.
根据上面的代码,我必须每一分钟得到响应。但我收到错误:听 EADDRINUSE。对此的任何帮助都将非常有帮助。
回答by vp_arth
This code makes http requests every minute:
此代码每分钟发出一次 http 请求:
var http = require('http');
var options = {
host: 'example.com',
port: 80,
path: '/'
};
function request() {
http.get(options, function(res){
res.on('data', function(chunk){
console.log(chunk);
});
}).on("error", function(e){
console.log("Got error: " + e.message);
});
}
setInterval(request, 60000);
回答by ariel_556
EADDRINUSE error is thrown because you can't start a server in the same port twice
EADDRINUSE 错误被抛出,因为你不能在同一个端口启动服务器两次
It would work of the next way:
它将按以下方式工作:
var express = require("express"),
app = express(),
recursive = function (req, res) {
console.log(req);
//Some other function call in callabck
res.send('hello world');
setTimeout(recursive, 100000);
};
app.get('/', recursive);
app.listen(8000);
}