我正在为node中的3个每日交易网站写一个通知器。我去解析网页的主体来获取细节。在细节中有一个定时器,说明交易将持续多久。我正在阅读计时器,并试图使用setTimeout/setInterval来设置何时函数应该再次执行。然而,函数调用是连续的,而不是等待。
我正在做的伪代码:
var getData = function(url) {
request(url, function(err, resp, body){
if(err) throw err;
//process the body getting the deal information and timer
setTimeout(getData(url),timer*1000);
}
getData(url1);
getData(url2);
getData(url3);
完整代码在这里。
我想让程序运行,不断调用自己的新的网页超时
我是一个Node.js新手,所以我猜我被事情的异步性质绊倒了。
感谢您的帮助。
编辑:更简单:
var hello = function(){
console.log("hello");
setTimeout(hello(),25000);
}
hello();
连续输出hello,而不是每2.5s输出hello。我做错了什么?
这个问题在您的hello
示例中很明显,所以让我们来看看:
var hello = function(){
console.log("hello");
setTimeout(hello(),25000);
}
hello();
特别是这一行:setTimeout(hello(),25000);
。也许你期待在25秒超时后呼叫hello
?它没有,它立即调用hello
,(这就是hello()
在Javascript中所做的,setTimeout
没有什么特别之处),然后它将hello()
的返回值传递给setTimeout
,这只有在hello()
返回另一个函数时才有意义。由于hello
递归地无条件调用自己,它永远不会返回,setTimeout
也永远不会被调用。它类似于下面的操作:
function hello() {
return doSomething(hello());
}
清楚为什么doSomething
永远不会被调用吗?
如果你想传递一个函数给setTimeout
,只传递函数本身,不要调用它并传递返回值:setTimeout(hello, 25000);
。
你的固定代码:
var getData = function(url) {
request(url, function(err, resp, body){
if(err) throw err;
//process the body getting the deal information and timer
setTimeout(getData, timer*1000, url);
});
};
getData(url1);
getData(url2);
getData(url3);
注意到我将getData
的参数作为第三个参数传递给setTimeout
。
当getData被调用时'request'正在运行。您希望getData
是您调用启动计时器的函数,还是加载数据的函数?
var getData = function(url) {
function doRequest(url) {
request(url, function(err, resp, body) {
if(err) throw err;
//process the body getting the deal information and timer
}
setTimeout(doRequest(url),timer*1000);
}
getData(url1);
getData(url2);
getData(url3);
你想要的是'setTimeout'指向一个函数(或匿名函数/回调),你在计时器到期后运行。正如您最初写的,getData
立即调用request
(然后在计时器后再次调用getData
)