user5088561
user5088561

Reputation: 3

setTimeout is not working

I'm new in Javascript and i'm good familiar with Thread.sleep in Java. As far as i know, Javascript uses setTimeout which is similar to Thread.sleep.

I'm using phantomjs to print my thread:

function doThing(i){
    setTimeout(function(){
        console.log(i);
    }, 100);
}

for(var i=1; i<20; i++){    
    doThing(i);
}
phantom.exit();

It prints nothing!!

Can you please let me know, what's wrong here? :(

Help would be appreciated!!

EDITED:

I'm using Java program for calling phantomjs script.

Upvotes: 0

Views: 630

Answers (5)

Alex Kopachov
Alex Kopachov

Reputation: 733

Try this

function doThing(i, last){
    setTimeout(function(){
        console.log(i);
        if (last) phantom.exit();
    }, 100 * i);
}

for(var i=1; i<20; i++){    
    doThing(i, i >= 19);
}

There are 2 fixes in this code (in comparison to origin):

  1. phantom.exit() must be called just after last operation will be finished (in my revision I resolved this by using flag 'last' which will be set to true only for last iteration);
  2. it's better to call setTimeout with slightly different timeout values, just to let them fire one by one (not so critical, but still it's better).

Upvotes: 1

Sreeraj
Sreeraj

Reputation: 21

Java and javascript are separate languages. So you can't compare features of those languages. setTimeout executes the block of code after a specified interval.

http://www.w3schools.com/jsref/met_win_settimeout.asp

Upvotes: 0

Hannes Johansson
Hannes Johansson

Reputation: 1802

Javascript's setTimeout is actually not the same as Thread.sleep at all. Javascript is single-threaded, and setTimeout just registers a callback to be executed after the provided amount of milliseconds, and then continues with the execution of the code following the setTimeout call. It doesn't halt the thread's execution.

Upvotes: 1

JotaBe
JotaBe

Reputation: 39014

Because the program finish before you allow it to print anything.

You should delay the phantom.exit(). For example you can include it in a setTimeout which delays it long enough after finishing the loop.

For example change your last line with this:

setTimeout(phantom.exit, 5000)

After five seconds phantom will close, and you should see the values printed in the console.

Upvotes: 0

Dickens A S
Dickens A S

Reputation: 4054

Try this

var i = 0;
function doThing(){
    console.log(i);
    i++;
    if(i<20) setTimeout(doThing, 100);
    if(i>=20) phantom.exit();
}

setTimeout(doThing, 100);

Upvotes: 0

Related Questions