Reputation: 3
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
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):
Upvotes: 1
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
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
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
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