2

I want to check a page every x (configurable) seconds in CasperJS. If a certain page element is present, then the script would continue with some extra steps before exiting. Otherwise it continues checking every x seconds. What code construct can be used for this?

The task is checking a particular eBay store if a (rarely listed) item exists. The question is essentially how to construct a while loop which is compatible with CasperJS promises. It will require refreshing the page.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
rgareth
  • 3,377
  • 5
  • 23
  • 35
  • 1
    Do you need to refresh the page, or just wait for an element to appear? Thanks. – alecxe Jan 04 '15 at 21:20
  • Might help anyway: http://stackoverflow.com/questions/16807212/how-to-wait-for-element-visibility-in-phantomjs – alecxe Jan 04 '15 at 21:21
  • Why don't you start with showing us what you've done so far. – Etheryte Jan 04 '15 at 21:22
  • The task is checking a particular eBay store if a (rarely listed) item exists. The question is essentially how to construct a while loop which is compatible with CasperJS promises. @alecxe it will require refreshing the page. – rgareth Jan 04 '15 at 21:34

1 Answers1

4

Since CasperJS' step functions (then* and wait*) are asynchronous and JavaScript doesn't have a blocking sleep function, this is easily solved using recursion.

function check(){
    if (this.getHTML().indexOf('some item') !== -1) {
        this.echo("found");
    } else {
        this.wait(x*1000).thenOpen(url).then(check);
    }
}

casper.start(url, check).run();

Another way is to use setInterval, but when you use it, you will break out of the CasperJS control flow. You will also have to prevent CasperJS from exiting. This is done by passing a callback into run (it can be empty).

casper.start(url, function(){
    setInterval(function(){
        casper.thenOpen(url, function(){
            if (this.getHTML().indexOf('some item') !== -1) {
                this.echo("found");
                this.exit();
            }
        });
    }, x*1000);
}).run(function(){});
Artjom B.
  • 61,146
  • 24
  • 125
  • 222