简体   繁体   English

casperjs无限循环超时不等待

[英]casperjs infinite loop timeout not waiting

Im using casperjs, im trying to get the content of a website that changes its values using websockets. 我正在使用casperjs,我试图获取使用websockets更改其值的网站的内容。 To accomplish this, instead of adding an event listener to each value, I just want to crawl the whole website every 10 seconds. 要实现这一点,我只想每10秒抓取整个网站,而不是为每个值添加一个事件监听器。

I have the following code: 我有以下代码:

casper.waitForResource("http://website.com",function() {
 getPrices(casper);
});

Inside getPrices, I'm able to scrap the values, and at the end i have the following lines: 在getPrices中,我可以废弃值,最后我有以下几行:

setTimeout(getPrices(casper),5000);

The problem is that I dont know why casper ignores the timeout. 问题是我不知道为什么casper会忽略超时。 It just calls it without sleeping. 它只是称它没有睡觉。 On the other hand, I dont think that this is the greatest solution, since its recursive and in the long run, it will end up with a memory stack. 另一方面,我不认为这是最好的解决方案,因为它是递归的,并且从长远来看,它最终会得到一个内存堆栈。

How can i accomplish this? 我怎么能做到这一点?

Thanks! 谢谢!

You are calling getPrices(casper) immediately and then passing that return value to setTimeout() , thus it doesn't wait for the timer to fire before calling the function. 您正在立即调用getPrices(casper) ,然后将该返回值传递给setTimeout() ,因此它不会在调用函数之前等待计时器触发。

Your statement of this: 你对此的陈述:

setTimeout(getPrices(casper),5000);

is like this: 是这样的:

var temp = getPrices(casper);
setTimeout(temp, 5000);

As you can see, that calls the function immediately and passes some return value to setTimeout() which is not what you want. 如您所见,它立即调用该函数并将一些返回值传递给setTimeout() ,这不是您想要的。

To fix it, change to either one of these: 要修复它,请更改为以下任一项

// pass anonymous stub function
setTimeout(function() {
    getPrices(casper);
},5000);

// use .bind() to create temporary function with the casper parameter bound to it
setTimeout(getPrices.bind(null, casper), 5000);

Calling a function repeatedly from a setTimeout() is not actually recursive. setTimeout()重复调用函数实际上不是递归的。 The stack completely unwinds before the setTimeout() fires so there is no stack build up. 堆栈在setTimeout()触发之前完全展开,因此没有堆栈构建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM