0

i was wondering how can I wait two times 5 seconds and do different things in each wait with phantomjs. Here's the code:

var page = require('webpage').create();

page.open("http://www.google.com/", function(status){

    var currentdate = new Date(); 

    console.log("\n\n" + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds() + "\n\n");


    setTimeout(function(){
        var currentdate1 = new Date(); 
        console.log("\n\n" + currentdate1.getHours() + ":" + currentdate1.getMinutes() + ":" + currentdate1.getSeconds() + "\n\n");
        return "hahaha";
    }, 5000);


    setTimeout(function(){
        var currentdate2 = new Date(); 
        console.log("\n\n" + currentdate2.getHours() + ":" + currentdate2.getMinutes() + ":" + currentdate2.getSeconds() + "\n\n");
        phantom.exit();
        return "hahaha";
    }, 5000);

});

Why is phantomjs the second setTimeout function is not working properly?? How can I solve this problem? The output i want to achieve is this:

16:13:10
16:13:15
16:13:20

And not this (as now it does):

16:13:10
16:13:15
16:13:15

Sorry for my bad english. Thanks

  • 1
    Both the timeouts starts **now**, and waits five seconds. You either nest one within the other, or you set the second one to 10 second. – adeneo Oct 23 '16 at 19:19
  • See this for reset first timer before start second timer: http://stackoverflow.com/a/315133/6908226 – iazaran Oct 23 '16 at 19:23
  • Why did you delete your [previous question](http://stackoverflow.com/questions/40205489/wait-x-amount-of-seconds-in-phantomjs) and create a new account? – Artjom B. Oct 23 '16 at 19:43

1 Answers1

2

setTimeout is asynchronous, when you start one, the code doesn't stop running, it goes on with the other pieces, where you start the second setTimeout. To solve your issue, you need to either change the second timeout's delay to 10000 or you need to start the second timeout inside the first one.

Bálint
  • 4,009
  • 2
  • 16
  • 27