javascriptphantomjscasperjsslimerjs

casperjs infinite loop timeout not waiting


Im using casperjs, im trying to get the content of a website that changes its values using websockets. To accomplish this, instead of adding an event listener to each value, I just want to crawl the whole website every 10 seconds.

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:

setTimeout(getPrices(casper),5000);

The problem is that I dont know why casper ignores the timeout. 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!


Solution

  • 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.

    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.

    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. The stack completely unwinds before the setTimeout() fires so there is no stack build up.