Thiago C. S Ventura
Thiago C. S Ventura

Reputation: 2602

PhantomJS timeline screenshot repeat same image

I'm trying to do a test creating screenshot timeline from this animation: http://bl.ocks.org/mbostock/1136236

This is the peace of code where I'm trying to generate the screenshots. The problem is that all the screenshots are the same, just the fist movement of the animation. Every screenshot should represent the next movement of the animation.

When I try to use the page.reload() the first screenshot works but the rest is just black.

var doTimeOut = function(i){
    window.setTimeout(function(){
        // page.reload();
        pageData = page.evaluate(function(){
            return document;
        });
        page.render('screenshot'+i+'.png');
    },300);
}

for (var i = 0; i < 200; i++) {
    doTimeOut(i);
};

What's the problem with my approach? Is it possible to do what I'm trying?

Upvotes: 0

Views: 64

Answers (1)

Vaviloff
Vaviloff

Reputation: 16856

Due to the asynchronous nature of javascript all calls of doTimeOut are happening at the same time - the program doesn't wait for one doTimeout to finish, it launches 200 callbacks that will be called in 300 ms.

To avoid a major rewrite you could schedule those callbacks by increasing timeout each loop:

var doTimeOut = function(i){
    window.setTimeout(function(){
        pageData = page.evaluate(function(){
            return document;
        });
        page.render('screenshot'+i+'.png');
    }, 300 * i); // <---- HERE
}

for (var i = 0; i < 200; i++) {
    doTimeOut(i);
};

Upvotes: 1

Related Questions